In the previous post, I showed how to create basic email templates using custom labels. This works well for simple templates that don’t need a lot of merge fields. In this post, I’ll show an alternative using Visualforce components.
First a high level overview. Rather than create a single email template, we will create one template for each language. We will then create a Visualforce component that retrieves the appropriate template, performs the merge and then outputs the content into another email template. Kind of confusing, but bear with me.
- Create Email Templates
Create an HTML email template for each language you want to use.
2. Create a Custom Label
Create a custom label that will store the Ids of the email templates created in step 1. You’ll just add a “translation” for each label that will contain the Id for the appropriate language. I’m not a fan of hard coding Ids and you could get fancier by using the API name of the email templates instead, but for simplicity sake, I’m just using Id here.
3. Create Apex Controller
Now we need an Apex Controller that can take an arbitrary email template Id, merge it with a record Id, and output the final result. The key here is we are going to use Messaging.renderStoredEmailTemplate that takes an email template Id, a what Id and a who Id and creates a merged email. See the gist below for the code.
4. Create a Visualforce Component
This component will return the HTML or text body of the merge email template. See gist below for the code.
5. Create Final Email Template
For the final email template, you need to create a Visualforce template that uses the component created above.
- For the subject, you have to use the Substitute function I used in the previous post because subject can’t use custom controllers.
- Set the language so the custom labels pull in the correct email template Id.
- Reference the component for both the html and plain text version.
In this post, I’ve introduced another way to dynamically translate your email templates. You can also use this technique to reduce the number of workflows and email alerts you create for other types of notifications. I’d love to hear other ideas you have on how to use the dynamic email component.