How can I change the subject of an email template dynamically in Apex? The following doesn't work because the subject line of the template overrides this value 'test':

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

Is there a solution or workaround?

2 Answers 2


The VF Email Template that you have designed,you can add <messaging:emailTemplate> tag in it at top.It will help you to add subject name dynamically if you are want to add field value in your subject line. Below is the example that explains how you can use above tag.

<messaging:emailTemplate subject="Opportunity {!RelatedTo.Name} Closed as {!if(RelatedTo.StageName =' Closed Won','Won','Lost')}"  recipientType="User" relatedToType="Opportunity"></messaging:emailTemplate>

recipientType & relatedToType are optional.


Good news: there is a workaround!

Basically it works by not setting the TemplateId like you would usually do, but instead rendering the template using a separate function, create an SingleEmailMessage with the rendered body and then override the subject. It works like this:

Messaging.SingleEmailMessage email = Messaging.renderStoredEmailTemplate(templateId, whoId, whatId);

That might be easier than you thought? :-)

See https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_messaging.htm

You must log in to answer this question.

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