[SalesForce] Change Visualforce email template subject in apex before sending the mail

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?

Best Answer

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.

Related Topic