I'm having trouble with email template merge fields that are not being populated when the email is sent by Apex.

I have an Apex method that uses setTemplateId, setWhatId, and SetTargetObjectId. The template is an HTML template, not Visualforce. setTargetObjectId is set to a contact. setWhatId is a custom object that has no relationships with the contact object.

In the email template, I want to merge {!Contact.Name}. When the Apex method runs, it sends the email and links the activity to the contact, but the contact name is always blank in the email body.

Is this because the merge fields must be in the WhatId custom object? Or because the contact is linked to a portal user?

Update: here is a portion of the code

        mail = new Messaging.SingleEmailMessage();

1 Answer 1


Looks like when one uses an email template it has to be tied to a contact. In order to do that i would just create a temporary contact as proscribed in the following SO answer:

Passing custom string into a Salesforce email template.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .