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);
efaList.add(efa1);
// 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;
mail.setOrgWideEmailAddressId(autoReplyAddress.get(0).Id);
mail.setFileAttachments(efaList);
listEmailToSend.add(mail);
//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?