1

I have create a Lightning email template related to Account. In the apex code I am referencing this email template, so that the email that goes out is based on this template. The email I receive is not the the template but what i have hard coded in the subject and body in the apex code.

[enter image description here][1

What changes do i make so that the email that goes out is based on the email template?

  public static void SendMail(String email,String recordId){
       EmailTemplate emailTemplate = [Select Id,Subject,Description,HtmlValue,DeveloperName,Body from EmailTemplate where name = 'VerifyDuplicateAccount'];
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       String[] toAddresses = new String[]{email};
       mail.setToAddresses(toAddresses);
       mail.setSubject('Verify duplicate Account');
       mail.setPlainTextBody('Hi, This record is duplicate : '+recordId);
       mail.setBccSender(false);
       mail.setUseSignature(false);
       mail.saveAsActivity = false;
       mail.setTemplateID(emailTemplate.Id); 
       mail.setWhatId(recordId); //This is important for the merge fields in template to work
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

}
3
  • Does the template subject and body display correctly if you remove the setSubject and setPlainTextBody in the apex? I know the setTemplateId should override it, but it's worth testing. Dec 8, 2019 at 16:57
  • Why are you setting the body and subject if you want to use a template? That will override the template, as explained in the documentation. Dec 8, 2019 at 21:30
  • I removed the setSubject and setPlainTextBody and got this error REQUIRED_FIELD_MISSING, Missing targetObjectId with template what i understand from the documentation is that i have to use setTargetObjectId(targetObjectId) where targetObjectId is the ID of the contact, lead, or user to which the email will be sent. Dec 9, 2019 at 16:05

0

You must log in to answer this question.

Browse other questions tagged .