Goal
- I'm attempting send a good looking HTML from Apex code, here's a stripped back screenshot .
- Based on the documentation I've reviewed, with Apex we can leverage SalesForce email templates using merge fields. I hope I'm understanding this correctly?
- In this case I want to merge in
Contact.FirstName
. I'm using the below code.
EmailTemplate et = [SELECT Id FROM EmailTemplate WHERE DeveloperName =:emailTemplateName]; List<string> toAddress = new List<string>(); toAddress.add(primaryEmail); Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setTemplateId(et.Id); mail.setToAddresses(toAddress); mail.setSubject('test subject'); mail.setTargetObjectId(primaryContact); mail.setWhatId(primaryAccount); mail.setSaveAsActivity(false); mail.setUseSignature(false); List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>(); allmsg.add(mail); try { Messaging.sendEmail(allmsg,false); return; } catch (Exception e) { System.debug(e.getMessage()); }
Properties
mail.setTemplateId(et.Id);
- I'm finding my email template in SalesForce. The template's "Available for Use" checkbox is thrownmail.setToAddresses(toAddress);
- I'm receiving the email at the address I'm sending to. I'm confident this is correct.mail.setSubject('test subject');
- this is correctmail.setTargetObjectId(primaryContact);
- the recipitient'sContact.Id
.mail.setWhatId(primaryAccount);
- the recipient'sAccount.Id
.
Result
- I'm successfully receiving the email, subject is coming across as I expect, but the body is empty.
- In SaleForce > Email Tematples, when I click the Send Test and Verify Merge Fields button, it works as expected, email looks great and that
Contact.FirstName
merges.
Moving Forward
I'm going to keep poking and hopefully answer my own question, but wondered if anyone has tackled this and gotten back a good looking HTML email with merged SalesForce data?