+ Start a Discussion
Harsh Chandra 23Harsh Chandra 23 

Send bulk emails to internal contacts through apex

Hi All,

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?

User-added image

Thanks,
Harsh
Ganesh Hembram 21Ganesh Hembram 21
Hi Harsh,

Try below code snippet
public void SendEmail()
{
 List<contact> lstcon=[Select id from contact limit 2];
 List<Id> lstids= new List<Id>();
 for(Contact c:lstcon)
 {
  lstids.add(c.id);
 }
 EmailTemplate et=[Select id from EmailTemplate where name = 'EmailTemplatename' limit 1];
 
 Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
 mail.setTargetObjectIds(lstIds);
 mail.setSenderDisplayName('System Admin');
 mail.setTemplateId(et.id);
 Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}

Please check below link to see all other method
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_mass.htm 


Regards,
Ganesh Hembram
Harsh Chandra 23Harsh Chandra 23
Hi Ganesh,

Using massEmailMessage also counting toward daily limitation. I executed your above code and daily limit counter reduced from 10 to 8.

Thanks,
Harsh