Concepts or coding lessons of Salesforce that you can implement easily

3 Easy Steps To Send Emails With Attachment From Your Apex Class In Salesforce

Messaging.Sendemail() : 


This method Sends the list of email objects instantiated which of either SingleEmailMessage or MassEmailMessage methods and returns a list of SendEmailResult objects.


Below are the easy steps or you can say template to Send an email with Apex with an attachment:


  • Create a list for email messages. 
  • Then create your emails.
  • Attach attachment to emails.
  • One by one (maybe in a loop)
  • Add them to that list. 
  • Finally send them using a Messaging.sendEmail(yourList).

Here, I will give you a step by step walk through of Send Emails With Attachment From Your Apex Class In Salesforce.
I have created one visual force page and controller associated with it. Visualforce page have Send Email With Attachment button. 

Once user click on the button, I am sending email with attachment using apex code. 

Step 1:

Create Apex Class with name DemoSendEmailWithAttachment. Copy and Paste below code snippet: 

public class DemoSendEmailWithAttachment
{
    public void SendEmailWithAttachment()
    {
        String subject = 'Closed won opportunities with Amount';
        String body = 'This is testing for Send emails with attachment from your apex class in Salesforce';

    // Creating the CSV file
    String finalstr = 'Id, Name, Amount \n';
String attName = 'Closed won opportunities.csv';

// get all the closed won opportunities
    for (Opportunity myOpportunity : [SELECT ID, Name, Amount FROM Opportunity WHERE StageName = 'Closed Won'])
        {
    string recordString = '"'+myOpportunity.id+'","'+myOpportunity.Name+'","'+myOpportunity.Amount+'"\n';
            finalstr = finalstr +recordString;
}
// Define the email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
// Create the email attachment    
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(attName);
efa.setBody(Blob.valueOf(finalstr));
// Set the paramaters to the email object
email.setSubject( subject );

// Here I am accessing current user email id to whom we are sending email
   email.setToAddresses( new String[] {UserInfo.getUserEmail()} );
email.setPlainTextBody( body );

// Attach file using setFileAttachments function
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r = 
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
    }
}

Step 2:

Create a VF page named as DemoSendEmailWithAttachment and paste the code below.

<apex:page Controller="DemoSendEmailWithAttachment">
    <apex:form>
         <apex:commandButton value="Send Email With Attachment" action="{!SendEmailWithAttachment}"/>
     </apex:form>
</apex:page>

Step 3:

You can click on Preview button which is on Visualforce page 
OR 
You can Go to the URL and type (Change the yoursalesforceinstance with your Salesforce org URL)

https://yoursalesforceinstance.com/apex/DemoSendEmailWithAttachment

Click on Send Email With Attachment button





Done !!!

Make sure all contacts have valid email address else email will bounced.

Before implementing mass email in Salesforce, you have to consider Email limits.

The maximum size of email attachment is 3 MB.
The create call restricts these files to a maximum size of 25 MB and For a file attached to a Solution record, then the file limit is 1.5 MB.

The API supports attachments on email message in create, delete, or update methods. The query call returns attachments parented by email, if the user performing the query has the “Modify All Data” permission else it does not returns attachments.

Enjoy! If you have any questions, comments, please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.




loading...

1 comment:

  1. Hi Nitish, great work. I used your code and it worked perfectly. But my requirement is to send the same file instead to email but to a FTP Server. Can you please help me with that.

    ReplyDelete