function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
levaleva 

Sending email from apex using template and merge fields

Hi,

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?

 

-Andy

levaleva

Hi Andy,

 

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

 

Thanks,

leva

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.

 

-Andy

levaleva

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
levaleva

Thank you, that worked

EguiEgui

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 ?

AngelikaAngelika

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

 

I have the same issue. Thanks

levaleva

Looping over list of cases. passing case id into template

 

for(Case c : cases){
  template = templates.get(c);
  Messaging.reserveSingleEmailCapacity(1);
  Messaging.SingleEmailMessage m = new Messaging.SingleEmailMessage();
  m.setTargetObjectId(c.ContactId);
  m.setTemplateId(template.id);
  m.setWhatId(c.id);
  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { m });
}

 

nagalakshminagalakshmi

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..

 

Thanks,

Lakshmi

SAHG-SFDCSAHG-SFDC
How to send to a group or users or Queue members? using a tempalte