Wednesday, November 30, 2016

Sending email with attached document by using Apex

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

How to create a document?

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



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

Query to get the id of the document :

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

Page:

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

</apex:page>

Controller:

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;
     }
}

No comments:

Post a Comment