I'm using the Messaging.SingleEmailMessage class to send an email (using a VF template), merging in some Case fields.

Where do you specify what record should be used for the merge fields in the template? In other words, how do I tell Apex what Case/Case ID to send to the template?

setTargetObjectId seems like it might be the method to use, and it's required if you're using a VF template - but it sounds like this has to be a Contact, Lead, or User - I also tried setting this to a flat Case ID and while there were no compile or runtime errors, the template didn't "receive" the Case ID.

Execute anonymous:

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] { 'test@test.com' });
email.setTargetObjectId('00563000000WyiwAAC'); // attempting to use a Case ID here does not result in a compilation or runtime error
email.saveAsActivity = false;
Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });


<messaging:emailTemplate subject="Template 1"  relatedToType="Case">
<messaging:plainTextEmailBody >

Visualforce Email Template.
<c:ConsumerCommunicationTemplate caseIdAttribute="{!relatedTo.Id}"/>


In the template, if I change the component markup to a flat Case ID like so:

<c:ConsumerCommunicationTemplate caseIdAttribute="00563000000WyiwAAC"/>

it works fine. This is the only reason I'm not sure it's an issue with the component and the order of instantiation of its constructor/getters/setters.

1 Answer 1


Your friend here is the setWhatId(someCaseId) method as documented here in the Apex doc

This corresponds to the {!relatedTo.Id} merge field in the VF email template that you can pass into your custom VF component

<c:ConsumerCommunicationTemplate caseIdAttribute="{!relatedTo.Id}"/>

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.