Skip to content

Instantly share code, notes, and snippets.

@sfdcale
Last active March 5, 2020 22:51
Show Gist options
  • Select an option

  • Save sfdcale/66a72ac9cf616c509ffbb799dc77a20e to your computer and use it in GitHub Desktop.

Select an option

Save sfdcale/66a72ac9cf616c509ffbb799dc77a20e to your computer and use it in GitHub Desktop.
This sample code attaches EmailMessage to Account record with content of EmailTemplate
public static List<EmailMessage> prepareEmailMessageList(List<Account> accList){
List<EmailMessage> emailMsgList = new List<EmailMessage>();
EmailTemplate templateObj = [SELECT Id,Name,Subject,Body,HtmlValue,Markup FROM EmailTemplate WHERE Name = 'Statement Template' LIMIT 1];
for(Account accObj: accList){
EmailMessage emailMsgObj = new EmailMessage();
emailMsgObj.status = '3'; // email was sent
emailMsgObj.relatedToId = accObj.Id;
emailMsgObj.fromAddress = 'Billing.Support@acme.com'; // from address
emailMsgObj.fromName = 'Billing Services'; // from name
emailMsgObj.toAddress = accObj.Email;
emailMsgObj.Subject = 'Your Statement is now available';
List<Messaging.RenderEmailTemplateBodyResult> resList;
resList =
Messaging.renderEmailTemplate(UserInfo.getUserId(), accObj.Id, new List<String>{templateObj.HtmlValue});
emailMsgObj.HtmlBody = resList[0].getMergedBody();
emailMsgList.add(emailMsgObj);
}
return emailMsgList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment