1

I have a requirement to send an email from a custom object and include any attachments from the notes and attachments section. These could be any file format from office docs and pdf's to images. Everything I've seen is for creating attachments and sending them or sending a link to the file in Salesforce. It has to be the actual file attached to the email. Is this possible?

1 Answer 1

4

You can simply do this:

       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'[email protected]'};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('[email protected]');
        mail.setSenderDisplayName('SFDC Support');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setTargetObjectId('005Q0000000Fo7f');
       // Give visualforce template id
        mail.setTemplateId('00XQ0000000iULj');
        mail.saveAsActivity = false;    
        
      //Set email file attachments
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :oppr])
        {
     // Add to attachment file list
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
        efa.setFileName(a.Name);
        efa.setBody(a.Body);
        fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);

      //Send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
1
  • Awesome! Now I just have to figure out how to do this on create. It's for BMC Remedyforce and when users create the record the attachments are stored in a temporary object not related to it, and the attachments are inserted after the custom object so they do not exist for a insert trigger. When they are inserted nothing is updated either. I'll have to trigger it off of the attachments object. Commented Oct 3, 2014 at 14:57

You must log in to answer this question.

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