+ Start a Discussion
RobinWRobinW 

Replace merge fields in Email Template messing with Html format

Hi All,

We would like to leverage the ease of use of Email Template's. This will allow a local administrator to easily generate the format they need for certain templates. However we have Merge Fields in there which are refering Looks Ups, Parent-Child relationships, ... of custom object.

An Apex controller has been written which will replace all merge fields in the email template with their data exuivalent. This is all working fine, but what happens now is that the letterhead of the email template is completely removed. Additionally, extra text is available (CDATA) in the form of ']]>', ... 

So what I actually do is I get the email template. Get it's html body, and do string search/replace on the merge fields. That html string is then pushed into the Messaging.SingleEmailMessage class and will then be send. Unfortunately with the wrong result.

Now I read that this CDATA text I'm seeing is actually where Salesforce merges the html content of the email template with the letterhead. Right before sending the email.

How can I overcome this issue? How can I get my letterhead? 

Kind Regards,
Robin 
Andy BoettcherAndy Boettcher
So here's a kind of "hack"....

You are correct when you state that Salesforce does the merging right as they send the email.  What I've done in the past is to:

1.  Insert a dummy contact or lead record (no account...private is OK)
2.  Construct and send the email
3.  Go back and pull the htmlBody from the SingleEmailMessage - do with that what you will
4.  Delete the dummy contact.