+ Start a Discussion

Send email using template to single address

It looks like if you specify a templateId on a Messaging.SingleEmailMessage object, you must also specify a TargetObjectId. That's fine if you are sending to an existing contact or user, but what if you just have an email address? Can you send an email using a template and just specify an email address? If not, any ideas on how to leverage a template in this manner?

Rasmus MenckeRasmus Mencke

If you are only sending to an email address, you can not use a template.


When we reneder a template we need to know what context it is in (contact, lead or user) to be able to merge data. Without the Contact or Lead ID you can not use the templates and will have to manage the email content in your code or maybe as a document.


I guess I am unclear on why a context is needed or, at least, why creating a Contact on the fly (not saving it to the database) and passing the object in is not an option.


We would like to leverage the email templates. So, as a work-around, we are sending the email both to an existing contact/user, specified in the TargetObjectId, as well as just an email address using setToAddresses. The documentation says this is not possible when using a template, but it does work. Just not the ideal solution.


It seems there is another potential problem I experienced when sending a MassEmailMessage with a temporary Contact, which is I end up deleting the Contact before the mail is actually sent out (i.e. the mail gets queued before it is sent out).  This leads to an invali_id exception because the Contact does not exist anymore. 


I believe that I could have the same problem with a SingleEmailMessage since it gets queued too and there still is a time window in which i can delete the temp Contact before the email is sent.  


Is there a callback mechanism i could use to delete the temp Contact only after the email has been sent (or a failure has occurred)?