[SalesForce] Get VisualForce Email Template as Blob

Similar to how we can use apex to get the blob value of a VisualForce page, can we also do this on a VisualForce Email Template? We need to get the rendered template into an attachment record in Salesforce.

Best Answer

One approach might be to factor the bulk of your Email Template code (which of course is just VF markup anyway) into a Visualforce Component. Thus enabling you to share it by referencing this component between a Visualforce Page (to enable you to capture it on your attachments) and Email Templates (for when your emailing). For example.

<apex:component access="global">
  <apex:attribute name="targetObject" type="Test__c" description="The context of the outer page / email templates" access="global"/>
  <h1>Congratulations</h1>
  <p>This is your new Component that is shared between your Email Template and Visualforce Page</p>
  <p>This is the name of your record {!targetObject.Name}</p>
</apex:component>

Your email template would look like this...

<messaging:emailTemplate subject="Test" recipientType="User" relatedToType="Test__c">
    <messaging:plainTextEmailBody >
        <c:ShareComponent targetObject="{!relatedTo}"/>
    </messaging:plainTextEmailBody>
</messaging:emailTemplate>

Your VF page would look like this...

<apex:page standardController="Test__c">
    <c:ShareComponent targetObject="{!Test__c}"/>
</apex:page>

Hope this helps!

Note: Note that Visualforce Components when delivered in Managed Packages are none editable, unlike Email Templates. You can work around this though, by copy and pasting the component code into a new one in the subscriber code and changing the template to point to the new component.

Related Topic