Sending Email – Sending a Document as an Attachment

What is a Document object? Document object in Salesforce represents a file that the user has uploaded. Now, this example helps you to understand sending documents as an attachment.

How to create a document?

  1. Login to Salesforce -> click all tabs (+) and click on Documents tab.
  2. Click on the new button, enter the required fields, upload the document and save. See below image for reference.

Sending Email

To send the document as attachment write a query to get the id of the document and pass this id in “setDocumentAttachments(ID[])” this method. This is the method in SingleEmailMessage class.


Document doc = [SELECT Id,Name FROM Document WHERE Name = 'DocName'];

See below example to send the document as an attachment.


public class SendingDocasattachmentExample {
	public pagereference sendDocAttach() {
		Document doc = [SELECT Id,Name FROM Document WHERE Name = 'Sample'];
		Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
		semail.setDocumentAttachments(new ID[]{});
		semail.setSubject('Sending Document as attachemnt example');
		String[] sendTo = new String[]{''};
		semail.setPlainTextBody('Please find the attached document details');
		Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
		return null;

“Documentattachment” ApexPage

<apex:page controller="SendingDocasattachmentExample">
<apex:form >
<apex:commandButton value="Send Doc" action="{!sendDocAttach}"/>

Click on Send Doc button, you will get an email to the address you have mentioned in above apex class.