+ Start a Discussion

Sending email from apex using template and merge fields


I am attempting to send email from apex class using a template. How can I pass values into the merge fields?


Thank you, appreciate the help  

Best Answer chosen by Admin (Salesforce Developers) 
Andy BoettcherAndy Boettcher

That would be "setWhatId" as long as your template is setup that way.

All Answers

Andy BoettcherAndy Boettcher

If you're using a Visualforce email template, you define how you want your data to be formatted / displayed when you create the template.  To pass the objects to fill those fields, you use the "Recipient" and "RelatedTo" attributes when you call the template object from APEX.


Does that help?




Hi Andy,


Thank you for the reply.The template I was given is a "regular" email template. Would visualforce template be a better option?




Andy BoettcherAndy Boettcher

If the template you were given meets the business need - stay with it.  Execution is pretty much the same:


You'll use setTargetObjectId to set your target (which will be a User, Contact, or Lead)

Then use setTemplateId to specify the ID of your template.




I am setting setTargetObjectId() setTemplateId() that part works fine. The issue is that I also need to pass a variable (Case Number) into the template istelf.

This is the part I am not sure how to accomplish


Thank you

Andy BoettcherAndy Boettcher

That would be "setWhatId" as long as your template is setup that way.

This was selected as the best answer

Thank you, that worked


Thanks for the tip.


and if we use the Messaging.MassEmailMessage 

and the method setTargetObjectIds instead of setTargetObjectId ?


Would setWhatIds work ?


Will it retrieve the right object for each line ?


Can you show me your code where you passed your variable (CaseId) into the template.


I have the same issue. Thanks


Looping over list of cases. passing case id into template


for(Case c : cases){
  template = templates.get(c);
  Messaging.SingleEmailMessage m = new Messaging.SingleEmailMessage();
  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { m });



Hi leva,


I am sending a mail merge template through visual force page. I need to merge the data in mail merge templates before sending.... Is it possible?? If possible please help me..




How to send to a group or users or Queue members? using a tempalte