1

I created an Email template in classic.

enter image description here

However, When I send this email via send test and verify merge fields I get the display as show in the HTML preview.

However, when I send the e-mail via apex I get no formatting at all and plain text.

Example of response. As you can see it has lost all formatting.

enter image description here

Example of APEX code.

for(test__c rta: prta ){

       EmailTemplate et = [SELECT Id,Subject, Body, BrandTemplateId FROM EmailTemplate WHERE Id =: '00X1X000000MSiu'];      

       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       string [] toaddress= New string[]{rta.Client_Global_Email_Main__c};

       mail.setToAddresses(toaddress);

       string subject = 'Hi ' + rta.Client_Global_Forename__c;


       mail.setTemplateId(et.Id);
       mail.setSenderDisplayName('Your doom');
       mail.setHTMLBody(et.Body);
       mail.setTreatBodiesAsTemplate(true);
       mail.setSaveAsActivity(true);
       mail.setUseSignature(true);


       mail.setSubject(subject);

       allMails.add(mail);
       smsChasing(rta.Client_Global_Tel_Mobile__c, rta.Id );
}    
Messaging.sendEmail(allMails);   

Question) How do I send an E-mail via APEX and preserve the formatting.

1

Do not use setHTMLBody, setTreatBodiesAsTemplate, or setUseSignature. Simply providing the template ID is sufficient to preserve the formatting and send the appropriate message. You will also need to use setTargetObjectId to set the correct merge fields.

| improve this answer | |
  • Thanks for comment, I have tried removing setHTMLBody, setTreatBodiesAsTemplate, or setUseSignature. When I removed setHTMLBody I get the following error. System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing targetObjectId with template: [] – user64707 Mar 19 '19 at 15:26
  • @user64707 As it says, you need to use setTargetObjectId, too. – sfdcfox Mar 19 '19 at 15:32
  • Thanks for the help. I added mail.setPlainTextBody(et.Body) and removed what you told me to, the formatting is preserved. – user64707 Mar 19 '19 at 15:37
  • @user64707 You do not need setPlainTextBody, either. The template takes care of this for you. – sfdcfox Mar 19 '19 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy