Skip to main content

Code reviews rule: Use of sendEmail in loops

Written by David Martin
Updated today

Use of sendEmail in loops

Why is this an issue?

Salesforce limits the number of Messaging.sendEmail() calls to 10 per transaction. Placing email sends inside a loop will quickly exceed this limit, causing the transaction to fail.

Examples

Example of incorrect code:

for (Contact c : contacts) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[]{c.Email});
mail.setSubject('Welcome');
Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{mail});
}

Example of correct code:

List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
for (Contact c : contacts) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[]{c.Email});
mail.setSubject('Welcome');
emails.add(mail);
}
Messaging.sendEmail(emails); // Single call, up to 5000 emails

How can I fix violations?

  1. Collect emails in a list: Build a list of SingleEmailMessage objects inside the loop.

  2. Send all at once: Call Messaging.sendEmail() once after the loop with the full list.

Note: A single sendEmail() call can send up to 5,000 emails.

Resources

Did this answer your question?