Normally to send an email with a template this is how you would do it.

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  1. You set the TargetObjectId which then is used to get an recipient email address.
  2. You tell it which template to use by ID.
  3. You tell it which object instance to reference by ID.

It seems that you cannot override the contact/targetobject email by manually setting the email to address:


This is a problem when you don't have an existing contact and you don't want to create one just to send an email.

So what is the best way to send an email using a common template that uses fields from an object to generate a dynamic html email body?

I know one way is to set a static resource with HTML and dynamically manipulate that HTML upon referencing it.

1 Answer 1


Why not create a contact, send email and then roll-back?

Savepoint sp = Database.setSavepoint();
Contact ca = new Contact(Name='Bla bla');
insert ca;

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

Messaging.sendEmail(new List<Messaging.SingleEmailMessage> {mail});

  • Well in my situation one of the reasons I don't want to create a contact is because the email might be associated with an actual contact. Which i can of course just look up the contact by email. But then again, the email might not be associated with a contact. So, i am left with having to insert extra logic that in my opinion shouldn't be necessary if all i want is to send an email. So I guess i'm just stuck with referencing a static resource or class. Mar 5, 2019 at 19:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .