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
Alex 2.0Alex 2.0 

Visualforce email template attach page with custom controller

Hi all,


I think the answer is no, but I'll ask anyway.


Is it possible to attach a visualforce page rendered as pdf that uses a custom controller, in a visualforce email template?


I saw a post that describes using a component, but I already have the page and the controller seems that it shouldn't take much to make that available as an attachment in an email template. It's kind of silly to have to duplicate things.


Are there any workarounds?






I haven't actually tried this but, I'm wondering if you could make an HTTP call from Apex to your Visualforce page that returns the PDF file and then take the resulting data and feed it into an EmailFileAttachment object. This way you could reuse the Visualforce page.


Yes, it is possible.


You'll have to create a custom component that references the custom controller. Then, place that custom controller within the <messaging:attachment> tags of your Visualforce email template.


For example, if you have the following custom controller that finds accounts named Smith:


public class findSmithAccounts {
private final List<Account> accounts;

public findSmithAccounts() {
accounts = [select Name from Account where Name LIKE 'Smith_%'];

public List<Account> getSmithAccounts() {
return accounts;


 You would refer to this in a custom component named smithAccounts (make sure it is access global):



<apex:component controller="findSmithAccounts" access="global">
<apex:dataTable value="{!SmithAccounts}" var="s_account">
<apex:facet name="header">Account Name</apex:facet>


Then, within your Visualforce email template, you would call the custom controller within <messaging:attachment>, making sure to render it as PDF:


<messaging:emailTemplate subject="Embedding Custom Controllers" recipientType="Contact" relatedToType="Account">
    <messaging:htmlEmailBody >
        <p>As you requested, here's a list of all our Smith accounts:</p>
        <p>Hope this helps !</p>

    <messaging:attachment renderAs="pdf">
    <c:smithAccounts />


What if I wanted the custom controller to use information provided in the account specified by relatedToType?  Is there a way for the controller class to access the account and render only contacts related to the provided account?