Newer Version Available

This content describes an older version of this product. View Latest

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:

See Best Practices for Rendering PDFs for details of which components are recommended for use in PDF attachments.

Note

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:

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:
Replace your attachmentPDF page like this:
Then add the custom component to render at the bottom of your previous sendEmailPage:

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:
Next, the Visualforce page that sends the email: