function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
alex_from_75015alex_from_75015 

Issue on sending attachment file by email in trigger

Hello

I have the following needed : whenever somebody attach a file to an opportunity "close won" I want to send an email with this attachment to somebody

So I have created a trigger but Issue I have is how to attach "attachment" to email I have tried :

1) mail.setDocumentAttachments : but this only works with document and not attachment !!!!

2) Messaging.EmailFileAttachment but I can't set the body : with a text file I receive a document badly encoded "sdsf" becomes "xœ+NI+NI", with a png file, trigger says "No body specified in the file attachment"

Here is my code :

 

trigger Send_Document on Attachment (after insert) {
for (Attachment evt : Trigger.new) {
        // Iterate over each sObject
        string parentid=evt.ParentId;
        string typeid=parentid.substring(0,3);
        if (typeid=='006')
        {
                    Opportunity myopp=[select id, StageName, Name, AccountId from Opportunity where id=:evt.ParentId limit 1];
                    if (myopp.StageName=='Close Gagnée')
                    {
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        String[] toAddresses = new String[]{};
                        toAddresses.add('alachmann@runmyprocess.com');
                                   
                       
                        Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
                        attach.setFileName(evt.Name);
                        attach.setBody(evt.Body);
                        mail.setFileAttachments(new Messaging.EmailFileAttachment[] {attach});
              
                        mail.setToAddresses(toAddresses);
                        mail.setSubject('Document');
                        mail.setHtmlBody('A document has been uploaded');
                       
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
        }
    }
}


Can somebody help me ?

Regards

 



Best Answer chosen by Admin (Salesforce Developers) 
alex_from_75015alex_from_75015

Hi

I had answer from SF premium support

Just have to add : attachment f=[select body from attachment where id = :evt.id]; attach.setBody(f.body); 

it seems that evt.body was not holding correct value : don't know why !!!!

Thanks