(Don’t) Send Emails with Apex!

Just came across a situation where suddenly the client started receiving this error:

SINGLE_EMAIL_LIMIT_EXCEEDED

I was surprised to see that since I never recommend to send emails using Apex. The limit of 5000 emails per day is too tight.

Following aspects should be driving the design:

  • Send emails through workflows/process builders etc.
  • If you have to send emails through Apex:
    • Bear in mind: you can specify 100 email addresses in To and 25 in CC/BCC fields for SingleEmailMessage
    • Do not send emails to internal users/portal users by setting setToAddresses, Use setTargetObjectId, this will allow you to send any number of emails to internal/portal users.
    • You can send mass emails to only contacts, person accounts, leads and internal users.
    • Crossing the Governor limit would result in unhandled exception. Voila!! reserveSingleEmailCapacity has come to the rescue.

e.g.

try {

    Messaging.reserveSingleEmailCapacity(1001);

} catch (Exception e) {
    // From Winter '14, this code is now executed.

    System.debug(e.getMessage());

}

 

If your code (in the current context) is going to exceed the organization’s daily limit, it will throw a HandledException: System.HandledException: The daily limit for the org would be exceeded by this request.

 

P.S.: In case you receive any of the following:

UNKNOWN_EXCEPTION, unable to send email:

SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile. Single email must be enabled for you to use this feature.:

Check the following:

Navigate to Setup > Email Administration > Deliverability to update the Access Level to All Email.

 

Hope that helps.

Ketan Benegal