Print this page

Why are my attachments getting corrupted when sent via email by an after insert trigger on Attachments?

Knowledge Article Number 000003634

If an after insert trigger on Attachments is used to send the inserted attachment via email, the attachment will be corrupted. This is a known issue that is due to the fact that the body is compressed in the context of the after insert trigger, and thus its size results reduced. Sending the compressed version of the attachment via emails renders a corrupted attachment.



The workaround is to look up the ID of each attachment and then to use SOQL to load the body for that Attachment ID. This will force the reload and therefore the decompression of the body blob value. 

You can try the following code and test it yourself:

trigger AttachmentAI on Attachment (after insert) { 
for(Attachment a : { 
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); 
efa.setbody([select body from attachment where id =].body); // instead of efa.setbody(a.body); 
email.setSenderDisplayName(' query management system'); 
email.setToAddresses(new string[] {''}); 
email.setSubject('Testing attachment issue'); 
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); 
Messaging.sendemail(new Messaging.SingleEmailMessage[] { email }); 


promote demote