+ Start a Discussion
CyclebiffCyclebiff 

Is this a good way to send attachments via APEX?

These notes assume you know how to work with the Messaging.SingleEmailMessage class. If anybody has a better way of doing this, let me know.

While building an APEX class that emails Case Owner, boss wanted to add the last few attachments of a Case to the email being generated.

 

1.) Instantiate SingleEmailMessage object:

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

 

2.) Query Attachments of whatever object type you want attachments on. I return the results to an Attachment[] array. Note - this is a good place to limit the number of attachments you want to return.

Attachment[] queryAttachment = [select Body, Id, Name, ContentType from Attachment where Parentid=:someCaseObject.Id order by CreatedDate DESC];

 

3.) Create an EmailFileAttachment[] array to hold each file, loop through the query and populate the array.

        Messaging.EmailFileAttachment[] allAttachments = new
        for(integer i=0;i<queryAttachment.size();i++)
        {
            Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment();
            fileAttachment.setBody(queryAttachment[i].Body);
            fileAttachment.setFileName(queryAttachment[i].Name);
            allAttachments[i] =  fileAttachment;
        }
Messaging.EmailFileAttachment[queryAttachment.size()];
 

4.) Now that our allAttachments array is populated, pass allAttachments to your mail object's setFileAttachments method:

        mail.setFileAttachments(allAttachments);
 

5.) Do the rest of your mail.methods to generate and send your email.

 

http://blog.psychopup.net/post/2009/10/15/Adding-Attachments-to-emails-via-APEX-in-Salesforce.aspx

 

CyclebiffCyclebiff

Step 3 edit:

       

       Messaging.EmailFileAttachment[] allAttachments = new Messaging.EmailFileAttachment[queryAttachment.size()];
        for(integer i=0;i<queryAttachment.size();i++)
        {
            Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment();
            fileAttachment.setBody(queryAttachment[i].Body);
            fileAttachment.setFileName(queryAttachment[i].Name);
            allAttachments[i] =  fileAttachment;
        }

WesNolte__cWesNolte__c
Looks good:)
SMasterSMaster

Hi All,

based on your suggestion, i have created the following code but i am getting the following error:

 

Illegal assignment from LIST<Attachment> to LIST<Attachment>

 

 

please suggest.........

 

public class testmail
{
 ApexPages.StandardController controller;   
 
 public opportunity_proposals__c q
 {
 get;set;

 }
 
 public Boolean selected {get; set;}
   
 String op = ApexPages.currentPage().getParameters().get('id');
 
 public Id oppr   
 {    get;set;    }       
 
 public testmail(ApexPages.StandardController ctrl)   
 {      
 oppr = ctrl.getRecord().Id;        
 }
 
 
 public PageReference emailAtt()
 {
 
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'SMaster@gmail.com'};
       // String[] toAddresses = 'oppr.SMEs_Email__c';

        mail.setToAddresses(toAddresses);
        mail.setReplyTo('SMaster@gmail.com');
        mail.setSenderDisplayName('CRM Support');
        //mail.setSubject('Mail with Attachment');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        //mail.setPlainTextBody('Your Email has been sent'); 
        mail.setTargetObjectId('005Q0000000FR7f');
        mail.setTemplateId('00XQ0000000QULj');
        mail.saveAsActivity = false;

 

        List<Attachment> c = new List<Attachment>();
        Attachment[] queryAttachment = [select Body, Id, Name, ContentType from Attachment where Parentid=:oppr];
        Messaging.EmailFileAttachment[] allAttachments = new Messaging.EmailFileAttachment[queryAttachment.size()];

        for(integer i=0;i<queryAttachment.size();i++)
        {
            Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment();
            fileAttachment.setBody(queryAttachment[i].Body);
            fileAttachment.setFileName(queryAttachment[i].Name);
            allAttachments[i] =  fileAttachment;
        }
         mail.setFileAttachments(allAttachments);


      Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     return null;  
       
     /*  
      //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 });
        return null;*/
}
}

 

 

WesNolte__cWesNolte__c

That is a bit strange. I'm curious why you've commented out that second block as I'd suggest doing something like that to avoid this problem.

 

Wes

SMasterSMaster

Hi Wes,

 

I have done the changes as you recommended... But i am getting the following error.....while saving my class.. Please sugegst...

 

Compile Error: Variable does not exist: Name

 

 

public class testmaill
{
  public Id oppr     {    get;set;    }       
 
 public testmaill(ApexPages.StandardController ctrl)   
 {      
 oppr = ctrl.getRecord().Id;        
 }
 
 
 public PageReference emailAtt()
  {
 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'SMaster@gmail.com'};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('SMaster@gmail.com');
        mail.setSenderDisplayName('CRM Support');
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setTargetObjectId('005Q0000000FR7f');
        mail.setTemplateId('00XQ0000000QULj');
        mail.saveAsActivity = false;
       
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Id, Name, Body, BodyLength from Attachment where ParentId = :oppr])
        {
          Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
          efa.setFileName(a.Name);
          efa.setBody(a.Body);
          fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        return null;
  }
}        

 

WesNolte__cWesNolte__c

Hey

 

Is there any more to the error message?

 

Wes

SMasterSMaster

Hi Wes,

 

Yes.. if i try to remove that error.... bu making name as string.....

 

i use to get the following error:

 

Error: Compile Error: Loop variable must be an SObject or list of Attachment

SMasterSMaster

Hi,

 

 

Please suggest the possible error that i might be doing...... in the code provided...

 

Thanks

WesNolte__cWesNolte__c

Hey,

 

I can only see one place that anything called name is used. You could try replacing this:

 

 efa.setFileName(a.Name);

 

with

 

 efa.setFileName('test');

 

See if that makes a difference. If it doesn't please post all your class code.

 

Wes