Is there a way to create an EmailMessage record with an associated File/ContentVersion AND set HasAttachment when created via Apex? Same example code in this question, however the only answer there is for Attachment not Files/ContentVersion.

It works as expected if the EmailMessage was created via Email-to-Case.

1 Answer 1


I have done a quick check and found that you can relate a file with emailMessage via apex. But hasAttachment does not become true. I have used contentversion's firstpublicationId field to relate the file with EmailMessage record.

EmailMessage emailMessage = new EmailMessage();
emailMessage.status = '3'; // email was sent
emailMessage.relatedToId = '5000o00002OhKjg'; 
emailMessage.fromAddress = '[email protected]'; // from address
emailMessage.fromName = 'Billing Department'; // from name
emailMessage.toAddress = '[email protected]';
emailMessage.Subject = 'Hello';

emailMessage.HtmlBody = 'Hello World';
insert emailMessage;

ContentVersion ContVerFile = new ContentVersion();
ContVerFile.VersionData = Blob.valueOf('string');
ContVerFile.Title = 'title'; 
ContVerFile.ContentLocation= 's';
ContVerFile.FirstPublishLocationId = emailMessage.id;
insert ContVerFile;
System.debug([SELECT Id,HasAttachment FROM EmailMessage WHERE Id =: emailMessage.Id]);

enter image description here enter image description here

According to docs, hasAttachment Indicates whether the email was sent with an attachment (true) or not (false).

You must log in to answer this question.

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