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
Ronen SlifkinRonen Slifkin 

sending SingleEmailMessage with setSaveAsActivity(true)

Describing the goal:
We have a need to send an email to an external email address (which we did) but we also wants salesforce to add a task for this action.

We managed to do this from a  send an email  button in the following way  (you can see in the image)


Screen after we pressed send an email button


The problem is that we can't reproduce this behavior with apex code.
we tried this with the code below : The Email sent but Task not created 

[ Please be advised - we do not want to use message.setTargetObjectId() becuase we don't want to send an email to the contact ]

List<string> toList = new List<string>();
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
toList.add('any@external.email');
message.setUseSignature(false);
message.setSaveAsActivity(true);
message.setSubject('Any subject);
message.setHtmlBody('any Body');
message.setWhatId('00111000007dqTk'); //  THIS IS AN ID OF THE SIMPSON'S FAMILY
message.setToAddresses(toList);
Messaging.sendEmail(message);
Best Answer chosen by Ronen Slifkin
Andy BoettcherAndy Boettcher
Hello Ronen!

You would do the insert/delete on the fly yes - so it would be saved in Salesforce only for the duration of your APEX execution.

All Answers

Andy BoettcherAndy Boettcher
You need the setTargetObjectId set to do this, BUT - in your code if you:

1.  Insert a "dummy" contact with a fake email address
2.  Set that contact's ID as your setTargetObjectId
3.  Send the email
4.  Delete the "dummy" contact

It's kind of a hack, but should work for you.
Ronen SlifkinRonen Slifkin
Hello Andy thank you for your reply , regarding step 1 , 4 do it needed to be done dynamically ? so the contact would not hae really to be saved in the contact object ?

TIA
Andy BoettcherAndy Boettcher
Hello Ronen!

You would do the insert/delete on the fly yes - so it would be saved in Salesforce only for the duration of your APEX execution.
This was selected as the best answer
Ronen SlifkinRonen Slifkin
Thank you very much
will notify when test the code
again thank you very much
Dharmendra BhuvaDharmendra Bhuva
You can have any existing contact from org and then you should call setTreatTargetObjectAsRecipient(false). This way it won't send email to contact even if you call setTargetObjectId(contact.Id).