+ Start a Discussion

Outbound Email using an email template


I know it's possible to send outbound email from an Apex Class using a template.  But what if the template has merge fields?  Will those merge fields be resolved correctly?  For example, lets say I have a custom object called XXX, and I create a trigger to call an Apex Class whenever a record of that custom object is created.  If the template has references to XXX merge fields, will these be resolved?

Yes, SingleEmailMessage and MassEmailMessage operate the same as sending an email and/or mass email through the UI, including merging the fields correctly for any objects that can be referenced by the template based on the targetObjectId and whatId fields are used on the sendEmail call.

I tried using the email.setWhatIds(); method and got an error saying it was an invalid ID, and that only "Cases, Contracts, Contacts, Leads and Opportunities" can have their ID's used as WhatId's.

Can I have any confirmation on this??

I was trying it with the "Event" Object trying to have an email template with some Event merge fields, that's how I saw the error.

- Patrick
Rasmus MenckeRasmus Mencke
The supported fields through the API are:
  • Account
  • Asset
  • Campaign
  • Case
  • Contract
  • Opportunity
  • Order
  • Product
  • Solution
  • Custom Objects
According to the Apex reference guide Events is not a supported object.

Thanks for the reply there Rasmus. I figured it may be something like that :)
The reason why you can't use Event or Task objects is because there is no way to link an activity to another activity (see the Related To field in the UI). Until activities can be related to each other through standard functionality, then Messaging.sendEmail will not be able to use these objects for target ID values.
try this: mail.setSaveAsActivity(false)