6

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();
        mail.setTemplateId(templateMap.get(duration).Template_ID__c);
        mail.setTargetObjectId(userMap.get(ctm.Person__c).ContactId);
        mail.setWhatId(ctm.Course__c);
        mail.setSaveAsActivity(true);
        mail.setOrgWideEmailAddressId(orgWideEmailID);
7
  • What happens when you set the WhatID?
    – Eric
    Commented Jul 27, 2015 at 23:58
  • I'm already setting the WhatId to the custom object that I mentioned. Commented Jul 28, 2015 at 3:55
  • Not sure what you mean by your question. Have you seen this particular question? salesforce.stackexchange.com/questions/1242/… Maybe that'll help you.
    – chrisjlee
    Commented Aug 6, 2015 at 19:16
  • @chrisjLee When I send an email and setTargetObjectId is set to a contact, the {!Contact.Name} merge field in the template does not display the contact's name -- it remains blank. Commented Aug 10, 2015 at 23:36
  • 1
    Possible duplicate of WHY Can't I Use SetTargetObjectId(UserId) and SetWhatId?
    – Adrian Larson
    Commented Feb 25, 2016 at 21:39

1 Answer 1

2

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 .