EmailMessages.getFormattedThreadingToken() returns the email threading token that is formatted with the correct prefix and suffix which is used in the Salesforce Email-To-Case threading. The returned token can be added to the Email Subject or Body so that when the users respond back, it will link the Email Message to the respective Case record in Salesforce.
Sample Apex Code:
/* START */
Id caseId = '500au00000560goAAA';
String formattedToken = EmailMessages.getFormattedThreadingToken(
caseId
);
Messaging.SingleEmailMessage emailMsg = new Messaging.SingleEmailMessage();
emailMsg.setToAddresses(
new String[] { '<EmailAddress>' }
);
emailMsg.setPlainTextBody(
'Test Email Notification'
+ '\n\n'
+ formattedToken
);
emailMsg.setWhatId(
caseId
);
EmailMessage latestIncomingEmail = [
SELECT ReplyToEmailMessageId, Subject
FROM EmailMessage
WHERE ParentId =: caseId
AND Incoming = true
ORDER BY CreatedDate DESC
LIMIT 1
];
emailMsg.setSubject(
latestIncomingEmail.Subject
);
emailMsg.setInReplyTo(
latestIncomingEmail.ReplyToEmailMessageId
);
OrgWideEmailAddress[] listOWEAs = [
SELECT Id
FROM OrgWideEmailAddress
WHERE Address = '<OrgWideEmailAddress>'
];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
if ( listOWEAs.size() > 0 ) {
emailMsg.setOrgWideEmailAddressId(
listOWEAs.get(0).Id
);
}
Messaging.sendEmail(
new Messaging.SingleEmailMessage[] { emailMsg }
);
/* END */
Here, EmailAddress is the Case Contact Email Address and OrgWideEmailAddress should be the Email Address where the Emails are getting forwarded to the Email-To-Case Service Email Address. So, the Email Address which forwards all the incoming emails to the Salesforce Email-To-Case Service Email Address should be added and verified in the Organization-Wide Addresses.