How to send email using apex

From Salesforce you can send emails using multiple methods. Commonly we will be image using workflows to send emails. But it is common to come across requirements that require more sophisticated email which might contain attachments. Please check below to see sample code to send email with attachments using apex,

Steps to Use

1) Get details regarding email body, attachments, to address etc.

    You need get some basic details and take some design considerations before starting development. Salesforce allows only 10 emails to be sent in one apex transaction. So if you are sending email from a trigger for each record it will fail, when data is loaded through data loader in bulk. In addition to this, there will be organization level limit in number of emails that can be sent in one day. But this limit is usually high(1000 x number of users).

3) Reuse below code to send simple email (minimum example)

    Please check below code sample to send a very simple email from apex.


3) Reuse below code to send email with attachment (full example)

    Please check below code sample to send email from apex.


This sample code receives a string of TO email addresses separated by commas, a String of CC email addresses separated by commas, email subject and email body as string. This method also creates a text attachment in the email.

4) Additional reference

    In addition to the methods used above there are many built in salesforce methods and supporting class related to sending emails. Please check below links for additional details,

Single Outbound email

Messaging Class

Send Email Result

4 comments: