I want to use email template with SingleEmailMessage for composing email. For one object I may send a few emails with different values in it. Email Template should be smth like this:

Hello {!Opportunity.LastModifiedBy},
Please take a <a href="surveyUrl">survey</a>.

The thing is that I want to generate surveyUrl in code for the same object and then send those different emails.
For example, for each Contact of Opportunity I want to send different emails for those Contacts. Template is the same, but value of surveyUrl variable is different.
At first, I wanted to use


but this don't allow me to set unique value of surveyUrl variable for all emails.
Is there any way I can use template and put object into email, but not it's id?

2 Answers 2


I guess the best thing you can do is to fill your tempMail with all the object's data, then try to send it and immediately rollback. This way it will be populated with data, but will not be sent. Then you can replace just the surveyUrl part with some apex, like:

//create some tempMail, set your 'whatId' etc. here
// (...)
Savepoint sp = Database.setSavepoint();
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {tempMail});

// (...) 
//create new email here, copy the body and replace url
mail.setHTMLBody(TempMail.getHTMLBody().replace('$$surveyUrl$$', someURL));

and then send single email for each recipient.


This code works:

List<EmailTemplate> t = [Select e.Name, e.Markup, e.HtmlValue, e.Body From EmailTemplate e where name like 'Template'];

Savepoint sp = Database.setSavepoint();
Contact c = new Contact(Email = '[email protected]', LastName = '[email protected]');
insert c;

List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new List<String>{'[email protected]'});

Messaging.sendEmail(emails); // Dummy email send

Database.rollback(sp); // Email will not send as it is rolled Back

system.debug(logginglevel.error, '\n - emails: ' + emails);

email.setHtmlBody(email.getHtmlBody().replace('surveyUrlPlaceholder1122', 'http://google.com'));
email.setPlainTextBody(email.getPlainTextBody().replace('surveyUrlPlaceholder1122', 'http://google.com'));

However, the problem is in insertion, which executes triggers and so on.
Just got an idea to get one Contact. If there is no Contact in the system, then 'create'.

You must log in to answer this question.

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