Salesforce Cookies #9

Populating merge fields in Salesforce Email Template without sending the email / Preview Email Template

Recently, I faced a challenge while working on a small project in which I had to send email through apex using email templates. I am calling it a challenge because of the problem I faced and I am sharing the solution/workaround I found for this.

Problem – The Email template was using custom fields of the Campaign Member object and whenever I was sending email to Campaign Member ( Lead ), those custom fields were not populating. I tried to set the WhatId to CampaignMember record Id but were getting an error in Messaging.sendEmail method. Unfortunately, I couldn’t use workflow/process builder as email’s from address had to be dynamically set based on some criteria.

Solution –  Used the renderEmailTemplate method of Messaging class and then set the merged body of the result as HtmlBody of the SingleEmailMessage object. Here didn’t get any error when I passed the campaign member record id as whatId.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String htmlBody = '';
EmailTemplate et = [SELECT Id, Subject, HtmlValue FROM EmailTemplate Where DeveloperName = 'Sample_Email_Template'];
email = Messaging.renderStoredEmailTemplate(et.Id, cm.LeadId, cm.Id);
mail.setTargetObjectId( cm.LeadId );
mail.setOrgWideEmailAddressId( orgWideEmailAddressId );
mail.setSaveAsActivity(false);

The above-mentioned approach can be used in many scenarios like

  1. If you want to preview Email Template content after populating all the merge field values.
  2. Where you can’t set the WhatId of the record directly for SingleEmailMessage object to render merge fields which are used in the email template.
  3. You want to send email to the user and can’t set the TargetObjectId field of the SingleEmailMessage object along with WhatId.
  4. Messaging.renderStoredEmailTemplate method takes 3 parameters, email template Id is the required one.

There are other variants of this method in Messaging class which you can found useful in your use case. You can get the rendered merge field with the help of GetHtmlBody() method of the SingleEmailMessage class from the returned object.

Resource –

Messaging Class