0

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

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setTargetObjectId(contact);
    mail.setTemplateId(templateID);
    mail.setWhatId(orderID);
  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:

        mail.setToAddresses(toAddresses);

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

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();
mail.setTargetObjectId(ca.Id);
mail.setTemplateId(templateID);
mail.setWhatId(orderID);

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

Database.rollback(sp);
  • 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. – FernandoG Mar 5 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.