function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SteveDevSteveDev 

Single Email Message with Template - Missing targetObjectId

Hi

 

I'm trying to send an email via apex using an email template.

 

The problem I'm coming across is that apparently I need to set the targetObjectId, even though I'm setting the toAddresses (and the documentation states that it only requires one of these to be populated).

 

Here's the code:

 

public static void bypassEmail(String email, String offerId) {

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

EmailTemplate et = [Select Id from EmailTemplate where Name = 'Bypass / Delegated Approval'];

mail.setWhatId(OfferId);

mail.setTemplateId(et.Id);

mail.setToaddresses(new String[] {email});

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

 

I can't set a targetObjectId as it needs to be sent to an address held in a custom field. Does anyone know a way to make this work or am I going to have to do a replace on the template Body to turn the merge fields into the values?

 

Thanks

 

Steve

spraetzspraetz

This is kind of unfortunate, but what I've done in the past is create a contact with the email in the standard email address field, insert it, then delete it after.

 

Adds a lot of DML statements to your code, but it was only way I could find as email templates only work with a few standard objects.

 

I'll look into the documentation issue where we say only one is required.  It sounds like we could add some doc around that.

HareHare
Hi 

here is solution http://hareeshgoudsalesforce.blogspot.in/2016/06/stop-sending-email-to-settargetobjectid.html