Skip to main content

Salesforce

Sending Emails With Apex: setToAddresses()

Christmas Online Shopping, Sales And Discounts Promotions During Winter Holidays, Online Shopping At Home. Female Hands On The Laptop With Credit Card And Blurred Bokeh Lights

Sending emails programmatically is a powerful feature in Salesforce, especially when you want to automate notifications or alerts. If you’ve been working with Apex, you may have come across different methods to send emails. One of the most versatile and commonly used methods is setToAddresses(). In this blog, we’ll dive into what it does, why you might choose it over other options, and how to implement it in your Salesforce projects.

 What is setToAddresses()?

setToAddresses() is a method provided by the Messaging.SingleEmailMessage class in Apex. This method allows you to specify one or more email addresses that you want the email to be sent to. Unlike setTargetObjectId(), which is used when sending an email to a Salesforce user, setToAddresses() gives you the flexibility to send emails to any valid email address, whether it belongs to a Salesforce user or not.

When Should You Use setToAddresses()?

setToAddresses() is particularly useful when:

  • You need to send emails to external recipients: If your email recipients are not Salesforce users, setToAddresses() is your go-to method. This could include customers, vendors, or partners who don’t have Salesforce accounts.

  • You’re sending emails to multiple recipients: You can pass an array of email addresses to setToAddresses(), making it easy to send an email to several people at once.

  • Your recipients are dynamic and not tied to Salesforce records: For example, if you’re sending an email to addresses pulled from a list in a custom object, setToAddresses() offers the needed flexibility.

How to Use setToAddresses() in Apex

Let’s look at a simple example. Suppose you have a requirement to send an order confirmation email to a customer once they place an order. The customer’s email is stored in a custom object called Order__c.

Here’s an example:

public class OrderConfirmationEmail {

    public void sendOrderConfirmationEmail(Id orderId) {

        // Retrieve the order record

        Order__c order = [SELECT Id, CustomerEmail__c FROM Order__c WHERE Id = :orderId LIMIT 1];

       

        // Create the email message

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

       

        // Set the email subject

        email.setSubject('Your Order Confirmation');

       

        // Set the email body

        email.setPlainTextBody('Thank you for your order. We will process it shortly.');

       

        // Set the recipient using setToAddresses

        email.setToAddresses(new String[] { order.CustomerEmail__c });

       

        // Send the email

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });

    }

}


In this example:

  • We first query the Order__c object to get the customer’s email address.

  • We then create a new instance of Messaging.SingleEmailMessage.

  • The setToAddresses() method is used to specify the recipient’s email address.

  • Finally, we send the email using Messaging.sendEmail().

Handling Multiple Recipients

One of the strengths of setToAddresses() is its ability to handle multiple recipients. Let’s extend the previous example to include a scenario where you need to send the same order confirmation email to multiple people, such as the customer, a sales manager, and a support team.

Here’s how you can do it:

public class OrderConfirmationEmail {

    public void sendOrderConfirmationEmail(Id orderId) {

        // Retrieve the order record

        Order__c order = [SELECT Id, CustomerEmail__c FROM Order__c WHERE Id = :orderId LIMIT 1];

       

        // Create the email message

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

       

        // Set the email subject

        email.setSubject('Your Order Confirmation');

       

        // Set the email body

        email.setPlainTextBody('Thank you for your order. We will process it shortly.');

       

        // Set the recipients using setToAddresses

        String[] toAddresses = new String[] {

            order.CustomerEmail__c,

            'salesmanager@example.com',

            'supportteam@example.com'

        };

        email.setToAddresses(toAddresses);

       

        // Send the email

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });

    }

}


Key Considerations

While setToAddresses() is powerful, there are some things to keep in mind:

  • Email Limits: Salesforce has limits on the number of emails you can send per day and the number of recipients per email. Be sure to familiarize yourself with these limits to avoid hitting them unexpectedly.

  • Error Handling: Always consider implementing error handling in your email-sending logic. For example, check that email addresses are valid before attempting to send.

Conclusion

setToAddresses is a versatile method for sending emails in Salesforce, especially when your recipients are not Salesforce users or when you need to send emails to multiple recipients. By understanding how and when to use it, you can make your Salesforce email automation more robust and flexible.

Whether you’re sending order confirmations, newsletters, or alerts, setToAddresses() gives you the flexibility you need to get the right message to the right people, every time. Happy coding!

Check out more articles below :

Sending Emails in Salesforce

Salesforce Documentation

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Reena Joseph

Reena Joseph, our Senior Technical Consultant at Perficient, boasts 3.5 years of experience and holds the prestigious 3x Salesforce Certified title. Her trailblazing spirit is evident with 100 badges on Trailheads, showcasing her commitment to continuous learning. Not limited to Salesforce, Reena has also mastered SQL and Programming in HTML5 with JavaScript and CSS3 on Hacker Rank. Beyond certifications, her passion for staying abreast of technological advancements is seen in her avid reading habits. In the dynamic tech world, Reena Joseph stands ready to drive innovation and inspire with her dedication to excellence.

More from this Author

Categories
Follow Us