How to use an Apex Email Service to store emails on a record EXACTLY as Salesforce does?
From what I understand, You don't need to create a task to insert an EmailMessage. Email message has relatedToId
field which you can use to directly link it to any desired record. As relatedToId is polymorphic like ParentId for Attachments, you should be fine.
Source: https://developer.salesforce.com/docs/atlas.en-us.212.0.api.meta/api/sforce_api_objects_emailmessage.htm
fancy Reply, Forward stuff : This can be easily handled by creating a record of
EmailMessageRelation
. It can only be created if email-to-case is enabled in your org.SRC : https://developer.salesforce.com/docs/atlas.en-us.212.0.api.meta/api/sforce_api_objects_emailmessage.htm
SRC: Send and Receive Email in Account,Lead,Opportunity,Quotes,Contact and maintain email loop
2. handling of email attachments : I don't fancy using standard Salesforce Attachment. Because attaching them to different records means cloning it and you cant' controll access(Determined by parent always). Creating a content version and linking it to email message looks the best solution to me. I recently created a utility method for linking email attachments to emailMessage as content document , you can refer it.
public void
createContentDocumentLinks(Messaging.InboundEmail.BinaryAttachment[] binAttachList,
Id insertedEmailMessageId) {
List<ContentVersion>cvList = new List<ContentVersion>();
List<ContentDocumentLink> cdlList = new List<ContentDocumentLink>();
if (binAttachList == null) {
return null;
}
for (Messaging.InboundEmail.BinaryAttachment binAttach : binAttachList) {
ContentVersion testContentInsert = new ContentVersion();
testContentInsert.Title = binAttach.fileName;
testContentInsert.VersionData = binAttach.body;
testContentInsert.PathOnClient = '/' + binAttach.fileName ;
cvList.add(testContentInsert);
}
insert cvList;
cvList = [select id, ContentDocumentId from ContentVersion WHERE Id in :cvList];
for (ContentVersion cv : cvList) {
ContentDocumentLink cl = new ContentDocumentLink();
cl.ContentDocumentId = cv.ContentDocumentId;
cl.LinkedEntityId = insertedEmailMessageId;
cl.ShareType = 'V';
cl.Visibility = 'AllUsers';
cdlList.add(cl);
}
insert cdlList;
}