[SalesForce] Send bulk emails to internal contacts through apex

I have a requirement to send email to campaign members(Contacts) through Apex. Read few blogs where they mentioned if I am sending emails to internal user, contact or lead using "setTargetObjectId" then it won't count under daily limit. So, I have written following code in my dev org to test:

Messaging.Email[] messages = new Messaging.Email[0];
EmailTemplate emt=[Select Id from EmailTemplate where DeveloperName = 'First_Campaign_Email'];
for(Contact objC : lstContact)
{
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setTargetObjectId(objC.Id);
    mail.setSenderDisplayName('System Admin');
    mail.setTemplateId(emt.Id);
    messages.add(mail);
}
Messaging.sendEmail(messages);

Now, assume lstContact contains 2 contacts and after executing above code when I check workbench for limits, I can see it's reduced to number of email sent. Infact, after sending 15 emails from above code, I started getting "SINGLE_EMAIL_LIMIT_EXCEEDED" exception. Please help what I am missing here and any idea to send bulk(10K) email to internal Contacts?

Best Answer

There's several different important limits to parse out on how Emails are counted. Full detail is under Outbound Email on the governor limits documentation.

There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity, case, campaign, or custom object pages

This statement refers to sending emails from the UI via interactions on the relevant record pages, as performed by a Salesforce user. It does not refer to sending bulk email in Apex.

If you use SingleEmailMessage to email your org’s internal users, specifying the user’s ID in setTargetObjectId means the email doesn’t count toward the daily limit. However, specifying internal users’ email addresses in setToAddresses means the email does count toward the limit.

You can send an unlimited amount of email to your org’s internal users, which includes portal users.

Here's where you get to avoid limits when sending in Apex. Your limits-free emails must be to a User of Salesforce, and you must use setTargetObjectId(myUserId) to specify the recipient.

If you address messages using an email address rather than a User Id, or if you are emailing anyone who is not a Salesforce User, the limit still applies. Unless your org has non-default limits,

You can send mass email to a maximum of 5,000 external email addresses per day per org based on Greenwich Mean Time (GMT).

But in a Developer Org, where I assume you are working,

Additionally, your org can send single emails to a maximum of 15 email addresses per day.

To achieve what you want, you'll need to either work with Salesforce to raise your email limits, or implement an external bulk email tool like Marketing Cloud, Marketo, or MailChimp.

Related Topic