Sending Email from Apex in Salesforce: A Complete Guide with Email Result

Automating emails in Salesforce using Apex allows you to send notifications, alerts, or customer communications based on specific business rules. Apex provides built-in classes that make this process straightforward. Additionally, to ensure the emails are being sent successfully, you can use the Messaging.SendEmailResult class to track the status of your emails.

In this guide, we’ll walk through how to send emails using Apex and also verify the email sending result using Messaging.SendEmailResult.

Why Use Email with Apex?

Emails sent from Apex are useful when you need:

  • Automated Notifications: Trigger emails based on events like new records or updated opportunities.
  • Custom Messaging: Craft dynamic email content using Salesforce data.
  • Tracking Results: Ensure your emails were successfully sent and handle any failures with precision.

Apex Email Process: Adding the Email Result

Salesforce provides two key classes for sending emails via Apex:

  • Messaging.SingleEmailMessage: For sending emails to individual recipients.
  • Messaging.MassEmailMessage: For bulk emails.

Here’s how you can send emails and track the result.

 Basic Email Setup with Email Result

To send an email and capture the result, we will use Messaging.SendEmailResult. This class provides details on whether the email was sent successfully and any associated errors.

public class EmailSenderWithResult {
    public void sendEmailWithResult() {
        // Create a SingleEmailMessage instance
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        // Set the recipient
        String[] toAddresses = new String[] {'example@domain.com'};
        mail.setToAddresses(toAddresses);

        // Set email subject and body
        mail.setSubject('Welcome to Our Service!');
        mail.setPlainTextBody('Hello, welcome to our service. We are glad to have you!');

        // Send the email and capture the result
        Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

        // Process the result
        for (Messaging.SendEmailResult result : results) {
            if (result.isSuccess()) {
                System.debug('Email sent successfully to: ' + result.getSuccessAddress());
            } else {
                System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
            }
        }
    }
}

Customizing the Email

Let’s take it one step further by personalizing the email content using data from a Salesforce record, like the Lead object, and tracking the email result.

public class EmailSenderWithResult {
    public void sendPersonalizedEmailWithResult(Id leadId) {
        // Query the lead
        Lead lead = [SELECT FirstName, Email FROM Lead WHERE Id = :leadId LIMIT 1];

        // Create an email instance
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        // Set recipient details
        mail.setToAddresses(new String[] {lead.Email});

        // Set dynamic subject and body using the Lead's first name
        mail.setSubject('Welcome, ' + lead.FirstName + '!');
        mail.setPlainTextBody('Dear ' + lead.FirstName + ',\n\nThank you for joining us!');

        // Send the email and capture the result
        Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

        // Check if the email was sent successfully
        for (Messaging.SendEmailResult result : results) {
            if (result.isSuccess()) {
                System.debug('Email successfully sent to ' + result.getSuccessAddress());
            } else {
                System.debug('Error in sending email: ' + result.getErrors()[0].getMessage());
            }
        }
    }
}

Handling Errors and Tracking Results

In many cases, you’ll want to track errors and notify admins or log these for troubleshooting. SendEmailResult gives access to a list of errors, if any, for each email attempt.

public class EmailErrorHandling {
    public void sendEmailWithErrorHandling() {
        // Create a SingleEmailMessage instance
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        // Set the recipient and email content
        mail.setToAddresses(new String[] {'invalid-email-address'});
        mail.setSubject('Test Email with Error Handling');
        mail.setPlainTextBody('This is a test email.');

        // Send the email and capture the result
        Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

        // Process results and handle any errors
        for (Messaging.SendEmailResult result : results) {
            if (!result.isSuccess()) {
                for (Messaging.SendEmailError error : result.getErrors()) {
                    System.debug('Email send error: ' + error.getMessage());
                    // Additional handling, like sending a notification to the admin
                }
            }
        }
    }
}

Bulk Email with Result Tracking

If you’re sending an email to multiple recipients, you can use MassEmailMessage. Let’s see how to send bulk emails and track the result for each recipient.

public class BulkEmailSenderWithResult {
    public void sendBulkEmailWithResult() {
        // Get a list of contacts
        List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE Email != null LIMIT 100];

        // Create MassEmailMessage instance
        Messaging.MassEmailMessage bulkMail = new Messaging.MassEmailMessage();
        bulkMail.setTargetObjectIds(new List<Id>(contacts));
        bulkMail.setSubject('Important Announcement');
        bulkMail.setPlainTextBody('This is an important update regarding your account.');

        // Send the bulk email and capture the result
        Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.MassEmailMessage[] {bulkMail});

        // Track the result
        for (Messaging.SendEmailResult result : results) {
            if (result.isSuccess()) {
                System.debug('Bulk email sent successfully.');
            } else {
                System.debug('Bulk email send error: ' + result.getErrors()[0].getMessage());
            }
        }
    }
}

 

Conclusion

Sending an email from Apex, combined with the Messaging.SendEmailResult class, gives you a powerful way to track the success or failure of email sends. This helps ensure that your communications are reliable and that any errors can be managed effectively.

Key takeaways:

  • Use Messaging.SingleEmailMessage or Messaging.MassEmailMessage to send emails.
  • Leverage Messaging.SendEmailResult to check whether emails were sent successfully.
  • Incorporate error handling to manage potential issues with email delivery.

By following this approach, you can build a robust email-sending mechanism in Salesforce while tracking results and improving the reliability of your communication processes.

5 2 votes
Article Rating