[SalesForce] How to send an Email Template via Apex

Goal

  • I'm attempting send a good looking HTML from Apex code, here's a stripped back screenshot 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 thrown
  • mail.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 correct
  • mail.setTargetObjectId(primaryContact); – the recipitient's Contact.Id.
  • mail.setWhatId(primaryAccount); – the recipient's Account.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?

Best Answer

In your code you need to bring in a slight change. Where you setting AccountId in setWhatId() method, change it to

mail.setWhatId(ContactId);

A brief explanation from the docs.

setWhatId(whatId) If you specify a contact for the targetObjectId field, you can specify an optional whatId as well. This helps to further ensure that merge fields in the template contain the correct data.

Related Topic