0

I want to edit the body of a HTML email template with Letterhead in Apex but keep the HTML formatting of the template intact. Using renderEmailTemplate() I'm trying to combine the Letterhead and email body but still getting a blank mail. Any idea what I'm doing wrong here? Hardcoded Ids just for testing.

*******************************************************************************
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
List<String> toAddress = new List<String>();
toAddress.add('0050L000009CpE6QAK');
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

List<EmailTemplate> emailBodyTemplates = [SELECT Id, Subject, Body, HtmlValue, BrandTemplateId FROM EmailTemplate WHERE Name = 'XXXXXXXXXXXX' LIMIT 1];


String emailBody = emailBodyTemplates[0].HtmlValue;
emailBody = emailBody.replace('{!TextToReplace}', 'TESTING TEMPLATE 123');
Id brandTemplateId = emailBodyTemplates[0].BrandTemplateId;


List<BrandTemplate> emailHeaderTemplates = [SELECT Value FROM BrandTemplate WHERE Id = :brandTemplateId LIMIT 1];
String emailHeader = emailHeaderTemplates[0].Value;


List<String> contentParts = new List<String>{emailHeader, emailBody};

List<Messaging.RenderEmailTemplateBodyResult> resList = Messaging.renderEmailTemplate('00Q2i000000tAUd', null, contentParts);

String compiledBody = '';
for(Integer i=0, len=resList.size(); i < len; i++){
    compiledBody += resList[i].getMergedBody();
}

mail.setHtmlBody(compiledBody);

mail.setSubject(emailBodyTemplates[0].Subject);
mail.setTargetObjectId('00Q2i000000tAUd');
mail.setTemplateId(emailBodyTemplates[0].Id);
mail.setTreatTargetObjectAsRecipient(false);
mail.setSaveAsActivity(false);
mail.setTreatBodiesAsTemplate(true);
mail.setToAddresses(toAddress);
mails.add(mail);
Messaging.sendEmail(mails,false);

*******************************************************************************
0

Try using the setter method on the SingleEmailMessage as per

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm#apex_Messaging_SingleEmailMessage_setHtmlBody

I am surprised you can write straight to mail.HTMLBody. Otherwise, view the intricacy between the setters for body content in the above document, it may be an issue with using both a template and a HTML body. The document states: 'Specify a value for setTemplateId, setHtmlBody, or setPlainTextBody. Or, you can define both setHtmlBody and setPlainTextBody.'

This to me implies you can only choose one of the three, or else both HTML and plaintext

  • My bad! Before posting I've tried setHtmlBody also but still it did not work. Anyway edited to setHtmlBody again. – DigantaSF Jul 29 '19 at 8:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.