Using email template in outbound emails

While sending outbound emails in apex we may need to use an existing email template(text or html or visualforce), in such a case it is mandatory to use target object id i.e lead/contact/user. Now, salesforce uses this object id for getting merge fields values, also it uses the email field from that object to send the mail to.

We may not need to send the email to that email id rather we may  have other email ids. But, in this case it will send the email to the target object email id. And it does not send the email to the mails set  in toAddresses. To avoid this and also make use of the email template we have to somehow get the body of the email template  within   our code. For this, just create a instance of outbound email object, set the email template along with a target object id, but then you have to make sure you roll back this steps so that the mail.

public class SendmyEmail {
 Public SendmyEmail(){
   //Create a dummy instance of outbound email object
   Messaging.SingleEmailMessage message= new Messaging.SingleEmailMessage();
   //set a roolback point
   Savepoint sp = Database.setSavepoint();
  //set desired email template id
   message.templateId = '00e90000560tji7p';
   // set the target object record id(this is mandatory while using email template)
   id recId = [select id from contact limit 1].id;
   message.targetObjectId = recId ;
   //fire dummy email
   messaging.sendEmail(new Messaging.SingleEmailMessage[] { message});
   //roll back to savepoint so that email is not sent
   Database.rollback(sp);
   //Create insatnce of actual email
   Messaging.SingleEmailMessage messageNEW= new Messaging.SingleEmailMessage();
   //get the bode from above dummy instance and set it to your actual email
   messageNEW.HTMLBody = message.getHtmlBody();
   //set desired email addresses
   messageNEW.toAddresses = new String[] { 'johncarly_1990@testmail.com' };
   //send the mail
   messaging.sendEmail(new Messaging.SingleEmailMessage[] { messageNEW});
 }
}

1 comment: