Sunday 22 February 2015

Populating Merge fields in Email Template through Apex

Hi All,

I have explained same in my previous post. Due to some demerit of previous post, i have gone by this approach.

Below is my previous post.
http://salesforceworld4u.blogspot.in/2015/01/populating-merge-field-in-email.html

http://salesforceworld4u.blogspot.co.uk/2013/12/sending-custom-object-information-in.html

Now new approach would be override merge filed of email template through apex code and leaving static text as it is so that user will modify according to their needs.

Below is code snippet

License__c lc = [select id,name,Account_Name__c from License__c  where id = 'a0q90000001Tq7f' limit 1];

EmailTemplate empTemp = [Select Id,Body, subject,Name from EmailTemplate where Name ='Email Template to notify before 15 days' Limit 1];

        String emailBody = empTemp.Body;
        String emailSubject = empTemp.Subject;
       
        emailBody = emailBody.Replace('{!License__c.Account_Name__c}', lc.Account_Name__c );

         
       
        emailSubject = emailSubject.Replace('{!License__c.Account_Name__c}', lc.Account_Name__c);
       
           
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'beheraa@brocade.com'};
  mail.setToAddresses(toAddresses);
       
     
        mail.setSubject(emailSubject);
        mail.setBccSender(false);
        mail.setPlainTextBody(emailBody);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

I hope it will solve all the problem related to populating merge field in email template.

No comments: