I want to replace the merge fields in my email templates with values I have in my class, with the intention of serving them in the front end for users to further edit.

My template looks like this:


 Requesting information on {!File__c.Full_Name__c}


 Hello, this is ({!User.Name}), requesting information on ({!File__c.Full_Name__c}).

My class is running the following

public void queryRequestedEmail() {
    try {
        requestedEmail = [SELECT Name, Body, HtmlValue, Subject FROM EmailTemplate WHERE ID = :requestedEmailString];
    } catch(Exception e) {
        System.debug('Requested Email cannot be found');


    String subject = requestedEmail.Subject;
    subject = subject.replace('{!File__c.Full_Name__c}', file.Full_Name__c);
    String requestedEmailBody = requestedEmail.HtmlValue;
    requestedEmailBody = requestedEmailBody.replace('{!User.Name}', user.Name);
    requestedEmailBody = requestedEmailBody.replace('{!File__c.Full_Name__c}', file.Full_Name__c);

    requestedEmailJSON = JSON.serialize(requestedEmail);

But the email I am getting back in the front end it the email with th emerge fields unpopulated.


You can use renderStoredEmailTemplate from Messaging. This takes a template Id, Who Id, and what Id, and returns the text that would be merged based on the records. This would be the easiest way to render a template assuming you can do so without querying additional records besides who Id, what Id, and template 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.