+ Start a Discussion
Joey HoJoey Ho 

Attachment on Email Message is empty when querying Attachments?

For anyone interested, the following Code is a trigger that send an email update to Case Owner, Case Contact and Case Team (users and contacts) in the Case everytime Case has been updated with an new Email-to-Case Message.


I have no idea why my list of Attachments is empty in the following lines of code??? The debug logs return 0 although my email test has attachments in the email and I can see this when going to the email Message record in the case.


list<Attachment> allAttachmentsInEmail = [Select Name, ContentType, Body From Attachment Where parentId =:e.id];

system.debug('---->number of attachments: ' + allAttachmentsInEmail.size());


Hope someone knows if I did something silly with my query?


Full code for those interested in using it.


trigger SendEmailUpdateOnEmailMessageForCase on EmailMessage (before insert, after insert) { 

		for(EmailMessage e: trigger.new){
			//system.debug('@@@###$$$%%^^ Inserted email' + 'trigger size = ' + trigger.new.size());
			string caseId = string.valueof(e.ParentId);
			if(caseId.startsWith('500')){	//This Email Message is for a Case 
				//Look up Case Details
				Case theCase = [SELECT Id, ContactId, OwnerID, Subject, Priority, IsClosed, EntitlementId, Description, CreatedDate, CaseNumber, AccountId, Email_Message_Body_Copy_For_Template__c  FROM Case WHERE Id =: caseId Limit 1];			
					if(e.TextBody != theCase.Email_Message_Body_Copy_For_Template__c){
						theCase.Email_Message_Body_Copy_For_Template__c = e.TextBody; //This field updates the Case so that we can dynamically merge field in the Template 'CASE_ICT_Customer_New_Case_Update'
							update theCase;
						}catch(dmlexception e2){
							system.debug('Problem with udpating Case sObject in SendEmailUpdateOnEmailMessageForCase: ' + e2.getMessage());
				}else if(trigger.isAfter){
					system.debug('***** the email Id is ' + e.id);
					Set<ID> toEmailId = new Set<ID>();;
					//Get Ids of the Case Team Members
					List<CaseTeamMember> member = [Select MemberId From CaseTeamMember where ParentId =:caseId];
					for(CaseTeamMember m: member){
					//system.debug('%%%List of Members %%%%% ' + toEmailId);
					//Get contact and user list from the set of Id's			
					List<Contact> listContactEmails = [SELECT Email FROM Contact Where ID IN: toEmailId];
					List<User> listUserEmails =  [SELECT Email FROM User Where ID IN: toEmailId]; 
					//Get all email address in unique set
					Set<String> setOfContactEmails = new Set<String>();
					Set<String> setOfUserEmails = new Set<String>();
					for(Contact c: listContactEmails){
					for(User u: listUserEmails){
					list<String> listOfEmails = new list<String>();
					//Create the email message body
					Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
					EmailTemplate emailTemp = [Select id From EmailTemplate Where developerName = 'CASE_ICT_Customer_New_Case_Update' Limit 1]; //A email template for Cases
					email.orgWideEmailAddressId = '0D2D0000000GnPW';	//Our Org Wide default
					email.replyTo = 'support.test@ictnetworks.com.au';
		      		        email.saveAsActivity = false;
					//Check for Attachments							
					system.debug('H$H$H$H$H Attachment Flag: ' + e.HasAttachment);
						//Create list of Messageing email File Attachments
						list<Messaging.EmailFileAttachment> fileAttachments = new list<Messaging.EmailFileAttachment>();
						//Query all child Attachments relating to this email Id
					        list<Attachment> allAttachmentsInEmail = [Select Name, ContentType, Body From Attachment Where parentId =:e.id]; 
						//Add to list of Attachments to email
						system.debug('---->number of attachments: ' + allAttachmentsInEmail.size());
						for(Attachment a: allAttachmentsInEmail){
							Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
					system.debug('@@@@@targetI ObjectID = ' + email.targetObjectId);
					system.debug('@@@@@emailTemp.Id = ' + emailTemp.Id);
					system.debug('@@@@@whatId = ' + email.whatId);
					//email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); 
					//Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
	} catch (exception e){
		System.debug('The following exception has occurred: ' + e.getMessage());






When you are working on an email message object. The attachments does not get stored to the Case object. So it will return null value on this. You have to write a separate trigger on Attachment object in order to capture the EmailMessage attachments related to the case Object.

trigger emailAttachment2Case on Attachment (before insert) {
    for( Attachment a : trigger.new ) {  
       if( a.parentid != null )
          String s = a.parentid;     
          if( s.substring( 0, 3 ) == '02s' ) // 02s is for emailmessage
              a.parentid = [select parentID from EmailMessage where id = :a.parentid].parentID;  // bulkify this line !!! 
Ajay Ghuge 6Ajay Ghuge 6

Hi Joe,

Have you resolved your issue ? 

I also need the solution for getting the attachments from the email.

@ajaybharath: I tried the trigger you posted but its not working. Is there any other way to get the email attachments ?

Alfredo Puente VasconcelosAlfredo Puente Vasconcelos
Hello, I have the same problem that the Attachments list is empty in a EmailMessage trigger. Has anyone resolved this problem?
Joey HoJoey Ho
Hi Alfredo,

I did tak Ajaybharath's advice and work off the Attachment object instead.

What happens is that the email message has to exist first before an Attachment gets created and associated to the email that it belongs to. Hence you have to work off the Attachments object which should trigger the same email communication chain as the trigger without any attachments. 

You have to use an after insert so that the Email Message can query the attachments when sending case emails.
trigger SendemailUpdateOnEmailMessageWithAttachmentForCase on Attachment (after insert) {

    for( Attachment a : trigger.new ) {
      // Check the parent ID - if it's 02s, this is for an email message
      String parentEmailMessageId = string.valueof( a.parentid );  
      if(parentEmailMessageId.startswith('02s')){  //Check if this Attachment is part of an Email Message  
        CompileCaseUpdateEmail compileAttach = new CompileCaseUpdateEmail();
        //a.parentid = [select parentID from EmailMessage where id = :a.parentid].parentID;
  } catch (exception e){
    system.debug('Error arising from running trigger "SendemailUpdateOnEmailMessageWithAttachmentForCase": ' + e.getMessage());
Hope that helps.