Using APEX to assemble HTML Letterhead Emails

I am looking to assemble an HTML Letterhead Email Template for an email service integration project.

There are two sObjects that hold this information – EmailTemplate and BrandTemplate.

BrandTemplate.value = broken HTML (styles aren’t associated to tags) Letterhead with CDATA tags throughout to hold the email Template info

EmailTemplate.HTMLValue = User-created HTML email template

I’ve been trying to merge the two (don’t need to worry about merge fields / codes) with little success.

I have tried turning both into XML, navigating the BrandTemplate.value field, but Salesforce does not natively support CDATA. I’ve also tried the polar opposite – stripping everything into text and doing replaces and substrings to assemble, but that also fails.

My end goal is to have a completed single HTML document consisting of both the BrandTemplate and EmailTemplate values.

Any hints / thoughts / clues?

Answer

Salesforce hacking time:
I had this exact requirement, and was stuck for a while because of the weird connection between EmailTemplate and BrandTemplate, and the inability to leverage a merging/parsing function however, I found a solution, this is far from a clean solution, but it seems to be working perfectly.

First what you will do is, create a single email message (like you would send it from apex):

// Here we will build the single email message
Messaging.reserveSingleEmailCapacity(1);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{'invalid@emailaddr.es'};
mail.setToAddresses(toAddresses);
mail.setUseSignature(false);
mail.setSaveAsActivity(false);
mail.setSenderDisplayName('MMPT');
mail.setTargetObjectId(UserInfo.getUserId());
mail.setTemplateId(sendTemplate.Id);

What we will do next is trick salesforce in sending the single email message, by setting a savepoint, sending the message and rolling back. The single email will not be send because of the rollback.

Savepoint sp = Database.setSavepoint();
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
Database.rollback(sp);

But now the beauty comes, because we triggered the sendEmail method, the email template got merged with the brandtemplate and the parsing took place. And you can find the parsed versions of your template components in the next variables (Subject, Text and HTML)

String mailTextBody = mail.getPlainTextBody();
String mailHtmlBody = mail.getHTMLBody();
String mailSubject = mail.getSubject();

This is far from what salesforce meant to do with single email message, and since we cannot leverage the platform parsing and merging functions, this did gave me a solution to this problem unfortunately through some hacking.

Attribution
Source : Link , Question Author : Andy Boettcher , Answer Author : pjcarly

Leave a Comment