+ Start a Discussion
Wei Dong 10Wei Dong 10 

How to fetch attachments through an EmailMessage

Hi,
I have created an EmailMessage, but I cannot fetch the name of the attachments through "EmailMessage.Attachments", so how? Any examples?
Vishal_GuptaVishal_Gupta
Hi Wei,

Please use the following query :

SELECT id,name FROM Attachment WHERE ParentId IN (SELECT Id FROM EmailMessage WHERE ParentId = '')

Please let me know if its work for you. 
Wei Dong 10Wei Dong 10
Sorry, I tried your code like this following:

1. I created an EmailMessage and handle the after insert trigger, so the ID is created:
User-added image

2. Then I attach a file jpg into the email, and click "Send", by referring this code like this:
List<Attachment> atts = [
    SELECT id,name FROM Attachment 
    WHERE ParentId IN 
    (SELECT Id FROM EmailMessage WHERE ParentID = '02s0m000000asfSAAQ')
    ];
System.debug(atts[0]);

3. But nothing is shown to me?? Error: List out of bounds.
Wei Dong 10Wei Dong 10
What's more——My mistake! 
SELECT Id FROM EmailMessage WHERE ParentID = '02s0m000000asfSAAQ'

Should be 'ID = 02s0m000000asfSAAQ'. But still nothing is shown :(
Wei Dong 10Wei Dong 10
EmailMessage msg 
    = [select e.TextBody,
       (select Name from Attachments)
       from EmailMessage e 
       WHERE e.Id = '02s0m000000asfSAAQ'
       ];

System.debug(msg.Attachments);

I also tried for an emailmessage with the attachment, but nope, attachments is empty……But actually I have the value!!!
User-added image

 
Vishal_GuptaVishal_Gupta
Hi Wei,

Please put the case Id in ParentId field, let me know if it will work.
Wei Dong 10Wei Dong 10
I wrote this in the "after insert" on Emailmessage, so how can I get the caseID in this trigger?
Wei Dong 10Wei Dong 10
Vishal_Gupta:

Even if I used what you said——CaseID, it still doesn't work :(
User-added image

The result is:
User-added image

This is the case:
User-added image
Arpan Muhuri 9Arpan Muhuri 9
Hi Wei,

Try querying from ContentDocumentLink instead ofAttachment.
Query : SELECT ContentDocumentId,Id FROM ContentDocumentLink WHERE LinkedEntityId IN (SELECT ID From EmailMessage WHERE ParentId = <Case Id>)
ContentDocument stores the body, type, size, etc. of the attached file.

Let me know if this works for you.
Thanks
Devendra_07Devendra_07
Hi All,

Please refer below queries that might help you to fetch the attachment:

1. Fetch ContentDocumentId  from ContentDocumentLink :
SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId IN (SELECT ID From EmailMessage WHERE ParentId = '5002w000004XXXXXX')

Note: We need to pass the case record's ID in the ParentID marked as bold above.

2. Then pass ContentDocumentId in below query:
Select Title, FileType,CreatedDate, ContentSize from ContentDocument where Id= 'ContentDocumentId '.

Please close this thread and mark as best if this resolves the issue.

Thanks.