function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Cory CowgillCory Cowgill 

Mail Template in Apex -Question - Create Email Body with Merge Fields?

Does anybody know if you can generate the text body of a MailTemplate inside Apex without sending an email?


For example, I want to genereate the body text of a MailTemplate for a preview screen before sending the email.


Another example, f you are creating a custom email page, and you want to mimic the functionality of the Activity Send Email page.


The standard email send page will generate the body text and put it on the page. Wondering if anyone has done similar for a custom VF page?

Cory CowgillCory Cowgill

I've found some other threads on this issue, but haven't found an answer.


I would rather not have to write a class which does the parsing logic with find/replace for the MailTemplate body and the input fields on my page, as that is kinda crazy, especially since Standard SF Screens are already doing this.


You can do this with Dynamic VF Components, which is a pilot fateure in Summer 11.


Controller code:

Id emailTemplateSelected ; // ID of an Email Template,
emailTemplateSelected = ... ;  // Your logic, or passed in thru VF

public Component.Apex.OutputText getPreview () {
   body = [select Body from EmailTemplate where Id = :emailTemplateSelected].Body ;
   Component.Apex.OutputText ot = new Component.Apex.OutputText() ;
   ot.expressions.value = body ;  // Note use of expressions, which allows you to dynamically use merge fields
   ot.rows = 10 ;
   ot.cols = 80 ;
   return ot ;


VF : 


<apex:outputText value="Here is a preview of your email"/>

<apex:dynamicComponent  componentValue="{!preview}"/>