2

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

email.setTemplateId(emailTemplateId);
email.setTargetObjectId(oppIdItem);

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

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});
Database.rollback(sp);

// (...) 
//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.

0

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 = 'qqqq@b.com', LastName = 'qqqq@b.com');
insert c;

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

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setTargetObjectId(c.Id);
email.setTemplateId(t[0].Id);
email.setWhatId('006M000000D7dgoIAB');
email.setToAddresses(new List<String>{'qqqq@b.com'});
emails.add(email);


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.setTargetObjectId(null);
email.setTemplateId(null);
email.setHtmlBody(email.getHtmlBody().replace('surveyUrlPlaceholder1122', 'http://google.com'));
email.setPlainTextBody(email.getPlainTextBody().replace('surveyUrlPlaceholder1122', 'http://google.com'));
Messaging.sendEmail(emails);

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'.

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.