using custom controllers in visualforce email templates

To be able to do some calculation or query some records to show on a visualforce email template we would certainly need a controller associated with VF email template. But a visualforce email template attribute [<messaging:emailTemplate>] does not allow direct association of controller with it. A workaround for this is, embedding a visualforce component that can use  controller with it. We can then use this component in the visualforce email template. 

Lets say, we want to display some randomly chosen accounts in the email template.This is not possible unless we query in the database to retrieve the records, hence we would use visualforce component to do the task.
For this, we would need to create a visualforce component,its controller and then use the component in the email template as below,

Controller for Visualforce Component
Public class accountList{
Public List accList{get;set;}
 Public accountList(){
  accList = new List([select name,id,description,accountnumber,annualrevenue from account limit 5]);
Visualforce Component

           Account Number
      Annual Revenue

Visualforce Email template

     This is your new Visualforce Email Template. Following are a list of randomly choosen accounts in my org:

Now when we use this email template it will populate the records from the visualforce component, as you can see in the screen shot below,
Some points that needs to be considered before using a visualforce component in VisualForce email template:
1. Make sure you specify the access as global for your compoennt, otherwise your email template would not compile and give below error, <messaging:emailTemplate> can only contain components with an access level of global. <c:accountlist> is not valid.
   <apex:component controller="AccountList" access="global">
2. Visualforce email template cannot contain pageblock and its child attributes(pageblocktable for example), also form cannot be included in vf email template, hence you cannot put this in the visualforce compoennt to be used in vf email template, for vf component would be a part of email template itself.

Related Posts


  1. can we add more than one custom controllers in the visualforce email template?