Thursday 24 September 2015

Replace content of the Email Template using Apex

There could be multiple scenarios where we need to replace few parts of the content while sending the email from Apex. Below is the example for the same

Apex Code:

    //Below fetches the email template which we want to use for email
    EmailTemplate et=[Select id, htmlValue, Body, subject from EmailTemplate where DeveloperName = 'xyz'];

    //for an example we will be sending the email to the below User
    User u = [select Id, UserName, FirstName from User where Id  =: UserInfo.getUserId()];

    String htmlBody = et.HtmlValue;

    //below replaces the UserName with current User Name
    htmlBody = htmlBody.replace('{!Receiving_User.Username}', u.Username);
    //below replaces the FirstName with current User First Name
    htmlBody = htmlBody.replace('{!Receiving_User.FirstName}', u.FirstName);

    String plainBody = et.Body;

    plainBody = plainBody.replace('{!Receiving_User.Username}', u.Username);
    plainBody = plainBody.replace('{!Receiving_User.FirstName}', u.FirstName);
    //Below list is not required, it is just to show that we can send multiple email as well
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setTargetObjectId(u.Id);
    mail.setSenderDisplayName('Support Group');
    mail.setSubject('Welcome! Your Account Details');
    mail.setSaveAsActivity(false);
    mail.setHtmlBody(htmlBody);
    mail.setPlainTextBody(plainBody);
    mails.add(mail);


    if(mails.size() > 0 ) {
        Messaging.sendEmail(mails);
    }

Note: 
  • plainTextBody is optional, Either TemplateId or serHtmlBody or plainTextBody should be present to send an email.

No comments:

Post a Comment