Wednesday, 21 January 2015

Populating merge field in email template while sending mail from apex.

Hi All,
You might have come across the issue of populating custom object info in email template dynamically. Suppose you have designed one email template having merge fields of contact object and one custom object. if you will send a mail from apex using singleEmailmessagApi then only contact merge field will be populated.This is an existing behavior of sfdc. How do we overcome this issue??

As we know if we will use setTemplateId method to set email template which we have already designed then we need to use setTargetObjectId method(Mandatory method ). 
setTargetObjectId only accept Contact,User and Lead id that is why  those object merge fields will be populated in email template. Now the question is how can we pass custom object id ?.

If we are setting contact id in setTargetObjectId  here then we can use another method called setWhatId,there we can pass custom object id.That means if we are sending mail to contact mail then we can pass custom object id so that all merge fields will be populated. 

Below is the snippet of code:-
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage ();
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

When we run this code we will get definitely exception, to overcome that make sure your custom object is enabled for activity history.There is check box when edit a object, we have to checked it. 

Then It will work for all user except portal, because portal user cant be owner of activity. For the portal user we have design email template in apex it self. Below is the post in this regards.