Newer Version Available
Creating an Email Attachment
If you want to add an attachment to your email, you will need to add only a few lines of code to your custom controller. Email attachments are Blob file types. To create an attachment, you need to use the Apex Messaging.EmailFileAttachment class. You must define both the file name and the content of an EmailFileAttachment object.
Adding a PDF Attachment
The following example demonstrates how to transform a PageReference to a Visualforce page rendered as a PDF into an email attachment. First, create a
page called attachmentPDF:
1<apex:page standardController="Account" renderAs="PDF">
2
3 <h1>Account Details</h1>
4
5 <apex:panelGrid columns="2">
6
7 <apex:outputLabel for="Name" value="Name"/>
8 <apex:outputText id="Name" value="{!account.Name}"/>
9
10 <apex:outputLabel for="Owner" value="Account Owner"/>
11 <apex:outputText id="Owner" value="{!account.Owner.Name}"/>
12
13 <apex:outputLabel for="AnnualRevenue" value="Annual Revenue"/>
14 <apex:outputText id="AnnualRevenue" value="{0,number,currency}">
15 <apex:param value="{!account.AnnualRevenue}"/>
16 </apex:outputText>
17
18 <apex:outputLabel for="NumberOfEmployees" value="Employees"/>
19 <apex:outputText id="NumberOfEmployees" value="{!account.NumberOfEmployees}"/>
20
21 </apex:panelGrid>
22
23</apex:page>Next, create the EmailFileAttachment object in the send() method of your custom controller.
The following examples must be placed before calling Messaging.sendEmail:
If your SingleEmailMessage object is named email, then
you associate the attachment like this:
1// Reference the attachment page, pass in the account ID
2 PageReference pdf = Page.attachmentPDF;
3 pdf.getParameters().put('id',(String)account.id);
4 pdf.setRedirect(true);
5
6 // Take the PDF content
7 Blob b = pdf.getContent();
8
9 // Create the email attachment
10 Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
11 efa.setFileName('attachment.pdf');
12 efa.setBody(b);1email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});Defining a Custom Component as an Attachment
By creating a custom component and using it on the Visualforce email form and to render the PDF for the email, users can see a preview of the content they are trying to send.
The following
markup defines a custom component named attachment that represents the attachment for the email:
1<apex:component access="global">
2 <h1>Account Details</h1>
3
4 <apex:panelGrid columns="2">
5
6 <apex:outputLabel for="Name" value="Name"/>
7 <apex:outputText id="Name" value="{!account.Name}"/>
8
9 <apex:outputLabel for="Owner" value="Account Owner"/>
10 <apex:outputText id="Owner" value="{!account.Owner.Name}"/>
11
12 <apex:outputLabel for="AnnualRevenue" value="Annual Revenue"/>
13 <apex:outputText id="AnnualRevenue" value="{0,number,currency}">
14 <apex:param value="{!account.AnnualRevenue}"/>
15 </apex:outputText>
16
17 <apex:outputLabel for="NumberOfEmployees" value="Employees"/>
18 <apex:outputText id="NumberOfEmployees" value="{!account.NumberOfEmployees}"/>
19
20 </apex:panelGrid>
21</apex:component>Replace your attachmentPDF page like this:
1<apex:page standardController="account" renderAs="PDF">
2 <c:attachment/>
3</apex:page>Then add the custom component to
render at the bottom of your previous sendEmailPage:
1<apex:pageBlock title="Preview the Attachment for {!account.name}">
2 <c:attachment/>
3</apex:pageBlock>If you want to make changes to both the attachment and the preview, the attachment custom component needs to be modified in only one location.
Example: Sending an Email with an Attachment
The following example shows
the previous sendEmail example with a custom
component that adds a Visualforce page as an attachment. First, the controller:
1public class sendEmail {
2 public String subject { get; set; }
3 public String body { get; set; }
4
5 private final Account account;
6
7 // Create a constructor that populates the Account object
8 public sendEmail() {
9 account = [SELECT Name,
10 (SELECT Contact.Name, Contact.Email FROM Account.Contacts)
11 FROM Account
12 WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
13 }
14
15 public Account getAccount() {
16 return account;
17 }
18
19 public PageReference send() {
20 // Define the email
21 Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
22
23 // Reference the attachment page and pass in the account ID
24 PageReference pdf = Page.attachmentPDF;
25 pdf.getParameters().put('id',(String)account.id);
26 pdf.setRedirect(true);
27
28 // Take the PDF content
29 Blob b = pdf.getContent();
30
31 // Create the email attachment
32 Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
33 efa.setFileName('attachment.pdf');
34 efa.setBody(b);
35
36 String addresses;
37 if (account.Contacts[0].Email != null) {
38 addresses = account.Contacts[0].Email;
39 // Loop through the whole list of contacts and their emails
40 for (Integer i = 1; i < account.Contacts.size(); i++) {
41 if (account.Contacts[i].Email != null) {
42 addresses += ':' + account.Contacts[i].Email;
43 }
44 }
45 }
46
47 String[] toAddresses = addresses.split(':', 0);
48
49 // Sets the paramaters of the email
50 email.setSubject( subject );
51 email.setToAddresses( toAddresses );
52 email.setPlainTextBody( body );
53
54 email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
55
56 // Sends the email
57 Messaging.SendEmailResult [] r =
58 Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
59
60 return null;
61 }
62}Next, the Visualforce page that sends the email:
1<apex:page controller="sendEmail">
2 <apex:messages/>
3 <apex:pageBlock title="Send an Email to Your {!account.name} Representatives">
4 <p>Fill out the fields below to test how you might send an email to a user.</p>
5
6 <apex:dataTable value="{!account.Contacts}" var="contact" border="1">
7 <apex:column>
8 <apex:facet name="header">Name</apex:facet>
9 {!contact.Name}
10 </apex:column>
11 <apex:column>
12 <apex:facet name="header">Email</apex:facet>
13 {!contact.Email}
14 </apex:column>
15 </apex:dataTable>
16
17 <apex:form><br/><br/>
18 <apex:outputLabel value="Subject" for="Subject"/>: <br/>
19 <apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
20 <br/><br/>
21
22 <apex:outputLabel value="Body" for="Body"/>: <br/>
23 <apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/>
24 <br/><br/>
25
26 <apex:commandButton value="Send Email" action="{!send}"/>
27 </apex:form>
28 </apex:pageBlock>
29
30 <apex:pageBlock title="Preview the Attachment for {!account.name}">
31 <c:attachment/>
32 </apex:pageBlock>
33</apex:page>