function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Roshan 10Roshan 10 

While sending email through Apex using Classic Email templates can we modify the contents of the email before sending

I would like to explore the option of sending email through Apex. I was reading through the Messaging.SingleEmailMessage class. Can we specify setTemplateId and then modify the contents of the template before sending
I am planning to have placeholder text in the template and before sending I would like to modify it in Apex
 
Abhishek BansalAbhishek Bansal
Hi Roshan,

Yes you can modify the content of the email in your apex class before sending it to the users, please have a look at the code snippet below:
EmailTemplate template=[SELECT Id,Body,Subject FROM EmailTemplate WHERE Id = 'xxxxxxxxxxx'];

template.body = template.body.replace('Placeholder Text', 'Text to be Replaced');

//You can also use HTMLValue if your content has HTML

Let me know if you need any other help on this.

Thanks,
Abhishek Bansal.​​​​​​​
Chris Nelson 12Chris Nelson 12
Nearly 2 years without an answer?  We can't have that.  This has likely been resolved, but for anyone searching for this answer, you want to use the method SingleEmailMessage.setTreatBodiesAsTemplate. Setting this to true will process the body as if it were a template.  You can retrieve your template in APEX and use the body, subject, etc. to build your email message while having control over other custom contents that may be specific to your use case and cannot be resolved with merge fields.

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_email_outbound_single.htm#apex_Messaging_SingleEmailMessage_setTreatBodiesAsTemplate