About the ‘Too Many Email Invocations: 11’ Error

By | October 22, 2020

Overview

The “Too Many Email Invocations: 11” error occurs when calling the sendEmail() method more than 11 times within a single transaction.

It does not mean that only 10 emails can be sent at once, but rather that the method can only be called 10 times.

Therefore, similar to avoiding governor limits on DML, there will be no problem if you correct the apex code so that the method is executed outside of the for loop.

Please note that if the email body is generated using the renderStoredEmailTemplate method, there is still a risk of encountering the SOQL query limit, because this method implicitly issues SOQL.

To mitigate this risk, it is necessary to change the generation of the email body so that it does not use the renderStoredEmailTemplate method.

Sample Code

NG

for(~){
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    String[] toAddresses = new String[]{'test@gmail.com'};
    String subject = 'This is a title';
    String body = 'The status code returned was not expected: '+response.getStatusCode() + ' ' + response.getStatus()+ ' ' + response.getBody();
    Id oweaId = [select id, Address, DisplayName from OrgWideEmailAddress Where DisplayName = 'test'][0].Id;

    mail.setToAddresses(toAddresses); 
    mail.setSubject(subject); 
    mail.setPlainTextBody(body); 
    mail.setOrgWideEmailAddressId(oweaId);
    mail.setUseSignature(false); 
    mail.setReplyTo('test@gmail.com'); 

    Messaging.sendEmail(mail);
}

OK

List<Messaging.SingleEmailMessage> listEmails = new List<Messaging.SingleEmailMessage>();

for(~){
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    String[] toAddresses = new String[]{'test@gmail.com'};
    String subject = 'This is a title';
    String body = 'The status code returned was not expected: '+response.getStatusCode() + ' ' + response.getStatus()+ ' ' + response.getBody();
    Id oweaId = [select id, Address, DisplayName from OrgWideEmailAddress Where DisplayName = 'test'][0].Id;

    mail.setToAddresses(toAddresses); 
    mail.setSubject(subject); 
    mail.setPlainTextBody(body); 
    mail.setOrgWideEmailAddressId(oweaId);
    mail.setUseSignature(false); 
    mail.setReplyTo('test@gmail.com'); 

    listEmails.add(mail);
}
Messaging.sendEmail(listEmails);