Is there any way to easily retrieve the Id of EmailMessage records after sending them via Messaging.SendEmail()?

Messaging.SingleEmailMessage m = new Messaging.SingleEmailMessage();
m.setToAddresses( new String[]{'heim@elastify.eu'} );
m.setSubject(     'test'  ); 
m.setHtmlBody(    '...' );
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { m });

Now how can I get the Id(s) of EmailMessage(s) generated as a result of the sending?

  • Messaging.SendEmailResult[] returns getErrors() and isSuccess() only. Jul 11 '18 at 12:06
  • 1
    @SantanuBoral Yes, I've seen that. Now it can be really hard to determine the correct Email via SOQL. Only thing I figure is to query for the newest email sent by the current user. But it feels bad. Also I'm not sure if Messaging.SendEmail might be an asynchronous process.
    – Uwe Heim
    Jul 11 '18 at 12:27
  • Your project sounds really interesting, based on all the questions you've been asking recently.
    – sfdcfox
    Jul 11 '18 at 18:21
  • @sfdcfox - really not a big thing - only sending/receiving some emails with attachments but having the need to do it "right".
    – Uwe Heim
    Jul 11 '18 at 18:26

You can't get the Id on the same transaction because the email messages are sent after the transaction succeeds. See items 19 and 20 on the Triggers and Order of Execution:

  1. Commits all DML operations to the database.
  2. Executes post-commit logic, such as sending email.

Email messages are then generated after the final commit. I think you can consider the send process as async, and the method call on Apex just as a confirmation of what the platform will attempt to deliver on said process.

What you can do is write a trigger on the EmailMessage object. You'll definitely get the Id there, and the relationship to the related object.

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.