10

My code is as follows:

List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage ();
email.setTemplateId(templateId);
email.setSaveAsActivity(false);
email.setToAddresses('raytest1@domain.com');
email.setTargetObjectId(leadId); //having email raytest2@domain.com
email.setWhatId(customObject.Id);
emails.add(email);
List<Messaging.SendEmailResult> results = Messaging.sendEmail(emails);

I want the email to be sent to raytest1@domain.com (the email sent in the setToAddresses method), but not raytest2@domain.com (the email of the targetObject, which is Lead.Email).

Is this doable?

20

Now we can use setTreatTargetObjectAsRecipient(treatAsRecipient) and treatAsRecipient as false.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm

1
  • Excellent! Great feature add...
    – Ray Dehler
    Sep 2 '16 at 23:45
2

Always templateId and targetObjectId walk hand in hand. If templateID is specified - email will always go to leadId

If you remove templateId- email will go to raytest1@domain.com

4
  • The reverse is also true. You can keep the templateId, but remove the setToAddresses line to only have the email sent to the Lead, Contact or User specified in the setTargetObjectId method.
    – dthrasher
    Jul 7 '15 at 19:24
  • Alas I need the template...
    – Ray Dehler
    Jul 7 '15 at 19:30
  • Templates are expected to have merge fields which are populated from TargetObjectID and WhatID. If your template is simple you can directly set body in code and send the email without using template. Jul 8 '15 at 8:11
  • Thanks! Answer is that it's not doable, and you provided a way to accomplish this.
    – Ray Dehler
    Jul 21 '15 at 16:09
2

Setting setTreatTargetObjectAsRecipient to false does the trick,

BUT

It does not save as an activity on that target.

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.