function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RJ12RJ12 

How to make merge fields work on an HTML email template sending through Apex?

I have an HTML email template with merge fields (from Lead object) in both subject and body.

I'm sending an email using the HTML template through apex, I'm able to populate merge fields in the email template Body but not on Subject.
 
EmailTemplate et = [SELECT Id,Subject, Body,HtmlValue FROM EmailTemplate WHERE DeveloperName ='Email_Template_Name'];
string toAddress='';
            
List<Lead> lstUpLead=new List<Lead>([Select id,Street from lead where id IN: lstTriggerNew]);
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();

  for(Lead objLeadUpdate : lstUpLead){

    toAddress=lstLead.Email;
    String[] sendingTo = new String[]{toAddress}; 
    semail.setToAddresses(sendingTo);
    semail.setSubject(et.subject);
    string plainBody=et.HtmlValue;
    plainBody=objLeadUpdate.Street!=null?plainBody.replace('{!Lead.Street}',objLeadUpdate.Street):plainBody.replace('{!Lead.Street}','....');
    semail.setHtmlBody(plainBody);
    semail.setTargetObjectId(objLeadUpdate.id);
    semail.setWhatId(objLeadUpdate.id);
    semail.setSaveAsActivity(false);
    semail.setTemplateId(et.Id);

}


Merge fields used in the HTML email template:
  • Subject:  {!Lead.FirstName}
  • Body:  {!Lead.Street}
Any help is highly appreciated.
Foram Rana RForam Rana R
Hi

I have gone through your code.
Your logic is correct. Can you please debug Lead.FirstName in for loop to check whether Firstname contains any value or not.

Let me know your thought.

Thanks,
Foram Rana