Apex

How to Send Email Using Apex in Salesforce?

How to Send Email in Salesforce using Apex Code

In this article you will learn how to send email using Apex in Salesforce.

We will use SingleEmailMessage class of the Messaging Namespace. This class has lot of methods which are helpful parameters like recipient, subject, body etc.

Code Time

Let’s have a look at the example and then we will see the purpose of each methods.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
String[] toAddresses = new String[] {'test@sampleemail.com'};
String subject = 'Salesforce Verse';
String body='Sending email using apex in salesforce successful.';
mail.setToAddresses(toAddresses); 
mail.setSubject(subject);
mail.setPlainTextBody(body);
mails.add(mail);
Messaging.SendEmailResult[] results = Messaging.sendEmail(mails);

for (Messaging.SendEmailResult res : results) {
    if (res.isSuccess()) {
        System.debug('Email sent successfully');
    }
    else {
        System.debug('The following errors occurred: ' + res.getErrors());                 
    }
}

Code Explanation

As i already told we will use the SingleEmailMessage class of the Messaging Namespace. In Line number 1 we created object of the SingleEmailMessage class. In line number 2 we created a list of SingleEmailMessage because the sendEmail method only accepts List. In line number 3,4 and 5 we create variables to store the recipient email, subject and body respectively.

Now coming to line number 6,7 and 8 as i already told you earlier that SingleEmailMessage class has various methods which can be used to set various attributes so here we are setting recipient email address, subject and body.

In line number 8 we are adding the mail instance to the list which we have created. In Line number 9 we are sending the email using sendEmail. After that we are looping on the results variable and logging the results.

In this article we have seen how to send email using apex in Salesforce. We have covered few methods but you can check out list of all methods in the SingleEmailMessage class from here.

Shubham Lashkan

Shubham Lashkan is a Salesforce Developer at Advanz101 with four years of experience. He's worked on various Sales Cloud projects and integrations with platforms like Facebook, Jira, and Twitter. He regularly shares his knowledge through articles and videos on his blog, YouTube channel, and Apex Hours.

Leave a comment

Your email address will not be published. Required fields are marked *