Salesforce | How to merge BrandTemplate with HTML body in VisualForce page

|
| By Webner

Problem: We tried to merge BrandTemplate with HTML body of Email template but haven’t got a proper solution (BrandTemplate is the letterhead object in Salesforce).

Solution: For now the problem is solved with a trick as we noticed that template is merged dynamically when email is sent.

Firstly we create a dummy email message (like we are sending normal email from apex):

Messaging.reserveSingleEmailCapacity(1);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{abc@gmail.com'};
mail.setToAddresses(toAddresses);
mail.setUseSignature(false);
mail.setSaveAsActivity(false);
mail.setSenderDisplayName('MMPT');
mail.setTargetObjectId(UserInfo.getUserId());
mail.setTemplateId(template_id);

Now we are performing a trick, by setting a savepoint, sending the message and rolling back. The email will not be sent because of the rollback:

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

As we triggered the sendEmail method, the email template got merged with the brandtemplate (so the merging took place at that time). Now you can find the parsed versions of your template components in the variables (Subject, Text and HTML):

String newHTMLbody= mail.getHTMLBody();
String plaintextbody = mail.getPlainTextBody();
String subject = mail.getSubject();

Now we have used these new variables and set these values to salesforce rich text component on Visualforce page.

Leave a Reply

Your email address will not be published. Required fields are marked *