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.

public class EmailUtility{
//Simple code to send email to a number of email addresses
public static void sendSimpleEmail(List<String> recipientList, String subject, String emailBody){
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(recipientList);
email.setSubject(subject);
email.setPlainTextBody(emailBody);
email.setHtmlBody(emailBody);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
/* After saving this class execute below code from developer console
* EmailUtility.sendSimpleEmail(new List<String>{'myemail@gmail.com'}, 'Subject Here', 'Body Here');
*/
}

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

    Please check below code sample to send email from apex.

public class EmailUtility{
public Boolean sendEmail(String emailTo, String emailCC, String emailSubject, String emailBody){
//Flag to track whether email is sent successfully
Boolean isSuccess = false;
//Body of attachment in email. It can be replaced with standard sf attachment
Blob body = Blob.valueOf('Sample Body for email attachment');
//Creating email attachmentattachment specifying content type and file name
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType('text/plain');
attach.setFileName('testAttachment.txt');
//Setting attachment as non-inline attachment.
attach.setInline(false);
//Assigning blob to email body
attach.Body = body;
//Creating singleEmailMessage object
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setUseSignature(false);
//Splitting TO email addresses and adding in array
String[] toAddresses = new String[]{};
for(String emailId:emailTo.split(',')){
if(emailId != null && emailId !=''&& emailId != ' '){
toAddresses.add(emailId.trim());
}
}
//Assigning TO address array
mail.setToAddresses(toAddresses);
//Splitting CC email addresses and adding in array
String[] ccAddresses = new String[]{};
for(String emailId:emailCC.split(',')){
if(emailId != null && emailId !=''&& emailId != ' '){
ccAddresses.add(emailId);
}
}
//Assigning CC address array
mail.setCCAddresses(ccAddresses);
//Setting reply to email address
//mail.setReplyTo('replyto email address');
mail.setSubject(emailSubject);
//Setting content of the email
mail.setPlainTextBody((emailBody==null?'This email body is empty':emailBody));
//Optionally you can use below line to add HTML formatted body for email
//mail.setHtmlBody('<h1>Dear User</h1>');
//Assigning attachment to email
mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });
//Sending email. If any execption occurs, it will be displayed in page
try{
List<Messaging.SendEmailResult> results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
if(results[0].success){
isSuccess = TRUE;
}else{
isSuccess = FALSE;
}
} catch(Exception ex){
isSuccess = FALSE;
}
return isSuccess;
}
}

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: