2

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();
email.setTemplateId(id); 
email.setSubject('test'); 

Is there a solution or workaround?

1

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.

1

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);
email.setSubject('Test');

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

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.