Problem: I am sending 1 confidential pdf for each contact. I am using SingleEmailMessage. When I include the Messaging.SendEmail() inside the For Loop and send it to no more than 10 contacts, each contact able to receive their respective pdf attachment but when I send it to more than 10 contacts, I am having "Too many Email Invocations" error due to Governor Limits. Now when I exclude the Sendmail() function from For Loop, I am collecting it in 1 List and SendEmail() all at once successfully, but all Contacts are receiving ALL PDF Attachments, not just their respective attachments. Anyone can help me with this? Thanks in advance!

List<Contact> listContactToEmail = new List<Contact>(); 
for(Contact c : [SELECT ID, Email FROM Contact WHERE id != null]) 
    List<Messaging.SingleEmailMessage> listEmailToSend = new List<Messaging.SingleEmailMessage>();
    Pagereference vfpage1 = Page.AutoGeneratePDFasPerContact;
    vfpage1.getParameters().put('id', ccc.Id);
    Messaging.EmailFileAttachment efa1 = SendEmail.CreatePDFAttachment(vfpage1, 'pdf', 'PDF Attachment for ' +c.Name);

// Initialization of emails.
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.targetobjectid = ccc.Case_Closure_Contact_Name__c;
                mail.templateid = emailTemp1.id;
                mail.whatid = cct.Id;

//When I put my SendEmail function here, it will only run for 10 invocations due to Gov limit.
(and this is bad practice).
                Messaging.SendEmailResult[] results1 = Messaging.sendEmail(listEmailToSend);

//When I put my SendEmail function here, it will send successfully but all of the attachments 
will be received by all of the contacts. Each contact has their own auto-generated PDF 
attachments so they should only receive what's theirs.

Messaging.SendEmailResult[] results1 = Messaging.sendEmail(listEmailToSend);

Do you have any suggestions?

  • 1
    The second way is, at a basic level, correct. I presume you must be doing something wrong in that code, but without seeing your code, the best we can give you is a guess. Please edit your question to include the relevant code so we can properly assist you.
    – sfdcfox
    Commented Oct 22, 2019 at 2:17
  • Hi. Already added the affected code. Thanks for noticing this question!
    – Noobie Dev
    Commented Oct 22, 2019 at 2:58

1 Answer 1


You are adding your attachments to efaLis, that's why in this line of code mail.setFileAttachments(efaList); you're attaching all existing pdfs in list to current mail.

Change this line on mail.setFileAttachments(new List<Messaging.EmailFileAttachment>{efa1}); and everything's going to be okay.

  • Thanks. This actually works! Also, clearing the efalist every loop works. Thanks Mariia!
    – Noobie Dev
    Commented Oct 23, 2019 at 19:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .