5

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);
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.