Pages

Friday, October 7, 2011

Reduce Deployment Pains (pt. 2): E-mail Templates

Here we are, nearing the end of the week, and as promised, here is part 2 of the "Reduce Deployment Pains" series. See what we did there with record types? Guess what? You can use the same idea for e-mail templates too. Say you're working with a method that is responsible for sending an e-mail. You can specify the individual parts of an email, the subject and the body, or you can specify an e-mail template. You'll want to shy away from using an ID again as sometimes you end up in situations where you have an ID mismatch between production and your sandbox.

Instead, like we did for obtaining a record type ID, we'll query the template by its name and use it later within a SingleEmailMessage.

public EmailTemplate template = [select Id,Name,Subject,body from EmailTemplate where name ='Your template's name here'];

...

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateID(template.id);
...