3 Ways to Call Email Templates from Apex

In the world of Salesforce development, Apex is a powerful tool that allows developers to create custom logic and automate various processes. One common task is sending emails, and Apex provides several methods to call and utilize email templates effectively. This article will explore three practical ways to call email templates from Apex code, offering a comprehensive guide for developers to enhance their email automation capabilities.
1. Using EmailTemplate.send()

The EmailTemplate.send() method is a straightforward and commonly used approach to sending emails from Apex. It enables developers to directly reference an email template and send it to one or more recipients. Here’s how you can implement this method:
EmailTemplate template = [SELECT Id, Name FROM EmailTemplate WHERE Name = 'YourTemplateName'];
String[] recipientEmails = new String[]{'recipient1@example.com', 'recipient2@example.com'};
Map emailContext = new Map();
emailContext.put('param1', 'value1');
emailContext.put('param2', 'value2');
EmailTemplate.send(template.Id, recipientEmails, emailContext);
In this example, EmailTemplate.send() takes three parameters: the email template's ID, an array of recipient email addresses, and an optional map for passing context variables to the template. The context variables can be used within the email template to dynamically populate content.
Advantages of EmailTemplate.send()
- Simple and easy to implement.
- Supports passing context variables for dynamic content.
- Allows sending emails to multiple recipients at once.
Considerations
While EmailTemplate.send() is a quick and efficient way to send emails, it may not be suitable for more complex scenarios. For instance, it doesn’t provide detailed control over the email’s rendering or allow for advanced customization.
2. Rendering Emails with Messaging.SingleEmailMessage

For more intricate email requirements, developers can leverage the Messaging.SingleEmailMessage class. This class offers extensive control over email content, allowing developers to dynamically generate and customize emails before sending.
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Set email properties
email.setToAddresses(new String[]{'recipient@example.com'});
email.setSubject('Your Email Subject');
// Set template ID and context variables
email.setTemplateId('YourTemplateId');
email.setTemplateValues(new Map{'param1': 'value1', 'param2': 'value2'});
// Send the email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
With Messaging.SingleEmailMessage, developers can not only set the template ID and context variables but also customize the email's subject, sender, and other properties. This approach provides more flexibility and control over the email rendering process.
Advantages of Messaging.SingleEmailMessage
- Offers advanced customization and control over email properties.
- Allows for dynamic rendering of email content.
- Supports various email attributes, including HTML content, attachments, and more.
Considerations
While this method provides extensive control, it may require more code and complexity, especially for simple email use cases. Additionally, developers need to ensure proper handling of errors and exceptions when working with Messaging.SingleEmailMessage.
3. Using Email Merge with Apex
Email Merge is a feature in Salesforce that allows for the automated merging of data from multiple sources into an email template. Developers can utilize Apex to trigger and control the Email Merge process, providing a streamlined way to send personalized emails to a large number of recipients.
List emailMerges = new List();
// Create an EmailMerge record for each recipient
for (Account acc : [SELECT Id, Email FROM Account WHERE ...]) {
EmailMerge emailMerge = new EmailMerge();
emailMerge.setTemplateId('YourTemplateId');
emailMerge.setRecipient(new EmailMergeRecipient(acc.Email));
emailMerge.setContextValues(new Map{'accountName': acc.Name});
emailMerges.add(emailMerge);
}
// Send the emails using Apex
Messaging.sendEmailMerges(emailMerges);
By using Email Merge, developers can easily send personalized emails to a large list of recipients without the need for complex loops or bulk operations. This approach is especially useful when dealing with large datasets or when email personalization is a key requirement.
Advantages of Email Merge
- Streamlined process for sending personalized emails to a large number of recipients.
- Simplifies the handling of complex email scenarios.
- Efficiently handles bulk email sending operations.
Considerations
Email Merge requires proper setup and configuration, including the creation of email templates and the mapping of data sources. Additionally, developers should be aware of potential performance implications when sending a large number of emails.
Conclusion
These three methods provide developers with a range of options to call and utilize email templates from Apex code. Whether it’s the simplicity of EmailTemplate.send(), the advanced customization of Messaging.SingleEmailMessage, or the streamlined process of Email Merge, each approach has its strengths and considerations. By understanding these methods, developers can choose the most suitable technique for their specific email automation needs in Salesforce.
Can I use HTML content in my email templates with these methods?
+Absolutely! Both EmailTemplate.send() and Messaging.SingleEmailMessage support HTML content. You can include HTML tags and styling in your email templates to enhance the visual appeal of your emails.
What happens if I don’t provide context variables for my email template?
+If you don’t provide context variables, the email will be sent with static content as defined in the email template. Context variables allow for dynamic population of content, so without them, the email will use the default values set in the template.
Are there any limitations on the number of emails I can send using these methods?
+Yes, Salesforce imposes limits on the number of emails that can be sent in a given time frame. These limits are designed to prevent abuse and ensure system stability. Developers should be mindful of these limits and plan their email sending operations accordingly.