Can we change the ParentId of EmailMessage Record in Salesforce

Requirement

If email-to-case feature is enabled, sending email creates EmailMessage and creates or updates Case based on thread. Sometimes emails sent (from customers in a new thread) are linked to already an existing Case and you come up requirement to link the EmailMessage record with existing Case instead creating new one. Please note that EmailMessage is linked with Parent Case using a lookup field ParentId.

It is possible to just alter the ParentId?

No, unfortunately the ParentId cannot be updated on an EmailMessage.

Workaround

  • Clone the EmailMessage and
  • Reparent that clone to the existing Case.
  • Delete the current EmailMessage record and Delete the new Case created.
//Clone the EmailMessage
EmailMessage emailMessage = [ 
	SELECT BccAddress, BccIds, CcAddress, CcIds,
	ContentDocumentIds, EmailTemplateId, FirstOpenedDate, 
	FromAddress, FromName, HasAttachment, Headers, HtmlBody, 
	Incoming, IsBounced, IsClientManaged, IsDeleted, 
	IsExternallyVisible, IsOpened, IsTracked, LastOpenedDate, 
	MessageDate, MessageIdentifier, ParentId, RelatedToId, 
	ReplyToEmailMessageId, Status, Subject, TextBody, 
	ThreadIdentifier, ToAddress, ValidatedFromAddress
	FROM EmailMessage WHERE Id =: emailMessageId]; 
];
EmailMessage clonedEmailMessage = emailMessage.clone();
//clonedEmailMessage.ParentId = ...update parentId with existing case id.
//clonedEmailMessage.TextBody = 'Testing';//Updating Body if needed
insert clonedEmailMessage;