1

I reviewed the documentation for the SingleEmailMessage but haven't found how to add the parentId (i.e. case Id) to the email message, is this even possible?

I want to be able to see the email on the 'Emails' related list on the parent case.

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.ToAddresses = new String[] {'[email protected]'};
message.setPlainTextBody('body test');

Messaging.SingleEmailMessage[] messages = new List < Messaging.SingleEmailMessage > {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
2

2 Answers 2

0

Actually SimpleEmailMessage is simply an apex class and its objects are not persisted to database. It is persisted in the database in EmailMessage after you send that message.

In order that attach that email to a case (or any other record), get that EmailMessage via SOQL query and then attach it to the desired record.

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.ToAddresses = new String[] {'[email protected]'};
message.setPlainTextBody('body test');

Messaging.SingleEmailMessage[] messages = new List < 
Messaging.SingleEmailMessage > {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
if(results[0].isSuccess()) {
    // Alter query such that only desired record is fetched.
    EmailMessage msg = [SELECT Id, ParentId FROM EmailMessage WHERE ToAddress = '[email protected]' LIMIT 1];
    msg.ParenId = 'aabbccddeeff123'; // Your record Id
    update msg;
}

If you are playing with many email messages, please bulkify the above code.

1
  • Are you sure about this? AFAIK ParentId is not updateable ;( Jan 16, 2020 at 10:30
1

use message.setWhatId(Id):

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.ToAddresses = new String[] {'[email protected]'};
message.setPlainTextBody('body test');
message.setWhatId(case.Id)
    
Messaging.SingleEmailMessage[] messages = new List < 
Messaging.SingleEmailMessage > {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .