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.
It is Not working and showing the error “Error: Compile Error: Method does not exist or incorrect signature: void setDocumentAttachments(List) from the type Messaging.SingleEmailMessage ”
May i know the reason
Hi Sachin,
Please use the below class.
public class SendingDocasattachment{
public pagereference sendDocAttach() {
Document doc = [SELECT Id,Name FROM Document WHERE Name = ‘XXXXX’];
list docid=new list();
docid.add(doc.id);
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
semail.setEntityAttachments(docid);
semail.setSubject(‘Sending Document as attachemnt’);
String[] sendTo = new String[]{‘xxxxxxxx.com’};
semail.setToAddresses(sendTo);
semail.setPlainTextBody(‘Please find the attached document details’);
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
return null;
}
}
setDocumentAttachments() was depricated by salesforce, so use setEntityAttachments() method instead
setDocumentAttachments is obsolete… try this method instead: semail.setEntityAttachments(new string[]{doc.Id});