[SalesForce] Invalid Message Id Reference – In-Reply-To Header is Not Valid

I am designing a custom mail application with Visualforce and Apex in salesforce and I'm running into some issues maintaining threads and setting reply to ids.

To establish which emails are a response to another email, I am utilizing the setInReplyTo method of the Messaging.SingleEmailMessage class, but I receive the following error:

SendEmail failed. First exception on row 0; first error:
INVALID_MESSAGE_ID_REFERENCE, In-Reply-To header is not valid.:
[In-Reply-To, 02s0t00000XXXXXXXX]

Upon navigating to the actual Id above, I am taken to a valid email message record.

Code:

EmailMessage activeEmail = [select Id from EmailMessage where CLAUSETOFINDMESSAGEHERE];
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.setInReplyTo(String.valueOf(activeEmail.Id));
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

Update:

I took a look at the headers in my received email from Salesforce and found the following:

Message-ID: <xxXXX000000000000000000000000000000000000000000000PP4SEN00dRKGMMwqTh20XXXXX__XXX@sfdc.net>

I would assume that this may be the id that the method is expecting, but I'm not sure where this is coming from or how it is generated.

I also attempted to use the EmailMessageId as the value for setReferences methods, but I receive the following error:

SendEmail failed. First exception on row 0; first error:
INVALID_MESSAGE_ID_REFERENCE, References header is not valid.:
[References, 02s0t00000XXXXXXXX]

In the documentation for MessageId and References, Salesforce links to: https://www.rfc-editor.org/rfc/rfc2822#section-3.6.4

message-id      =       "Message-ID:" msg-id CRLF

in-reply-to     =       "In-Reply-To:" 1*msg-id CRLF

references      =       "References:" 1*msg-id CRLF

msg-id          =       [CFWS] "<" id-left "@" id-right ">" [CFWS]

id-left         =       dot-atom-text / no-fold-quote / obs-id-left

id-right        =       dot-atom-text / no-fold-literal / obs-id-right

no-fold-quote   =       DQUOTE *(qtext / quoted-pair) DQUOTE

Best Answer

Try this:

EmailMessage activeEmail = [SELECT ReplyToEmailMessageId FROM EmailMessage WHERE ____];

message.setInReplyTo(activeEmail.ReplyToEmailMessageId);