Bulk E-mail Best Practices
Design considerations for sending bulk e-mails in a transaction.
Say we have an extensive list of users, all of whom need to be sent an e-mail. We build a simple for each loop that sends the e-mail, then marks it as sent in the database.
If an error occurs on our database action, did the e-mails processed before that error send? The answer is yes! When the send e-mail action is called, that e-mail is sent to a sending queue¹ to be processed. Any exceptions in the flow will not roll back e-mails sent before it occurs.
With this in mind, we can follow a couple of best practices to ensure the optimal design of our bulk e-mail code.
Best Practice 1: Mark the database before the e-mail is sent
If we’re sending e-mails in a loop followed by some other code and an error occurs, the e-mail preceding the error will be sent anyway. A better practice is to run our code before we send the e-mail – this way, when an error occurs, the action will halt before the e-mail is sent.
It’s also essential to monitor the platform logs when sending e-mails to catch these errors when they occur.
Best Practice 2: Include a commit transaction
Again, if we’re sending e-mails in a loop alongside other code and an exception is thrown, the e-mails will send, but the other database actions won’t be committed. Therefore, it’s a good idea to include a “Commit Transaction” action after our database calls.
When you call the send e-mail action, that e-mail is sent to the queue immediately. If an error occurs in the transaction, e-mails processed up to that point will be sent. Monitoring the platform when sending e-mails is essential.