In Salesforce, Using the SingleEmailMessage class in Apex, we can send an email with attached document in Salesforce. The class enables developers to easily automate sending emails and attach documents.
Specifically, developers first populate an email message using the SingleEmailMessage object. These include the recipients (setToAddresses()), subject (setSubject()), body (setPlainTextBody() or setHtmlBody()). In case of attachments, the setDocumentAttachments() method is used by passing the Salesforce document ID to attach the document with email. All of these IDs relate to documents that are already saved in Salesforce.
After that, using Messaging the email is sent complete with attachments. sendEmail() method. This allows enterprises to deliver essential papers such as invoices, contracts, or reports automatically via workflows or triggers.
The solution helps improve the basic email messaging functionality that Salesforce provides by integrating automation and document sharing, increasing communication efficiency and accuracy during real-time business processes.
This process enables developers to automate email communication and, at the same time, include relevant documents for their recipients. Below is a step-by-step guide on how to achieve this using Apex:
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?
- Login to Salesforce -> click all tabs (+) and click on Documents tab.
- Click on the new button, enter the required fields, upload the document and save. See below image for reference.
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.
Query
Document doc = [SELECT Id,Name FROM Document WHERE Name = 'DocName'];
See below example to send the document as an attachment.
ApexClass
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[]{doc.id}); semail.setSubject('Sending Document as attachemnt example'); String[] sendTo = new String[]{'XXXXXXXX@gmail.com'}; semail.setToAddresses(sendTo); 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}"/> </apex:form> </apex:page>
Click on Send Doc button, you will get an email to the address you have mentioned in above apex class.