+ Start a Discussion

Apex class to separate an attachment from the Email sent to Salesforce from web mail



Iam sending an email with attachment from Gmail to SalesForce


I want to develop an Apex class which retreives that Email and separate the attachment from that email


Any help or suggestion on this is greatly appreciated








Message Edited by apexdevSunil on 02-02-2009 01:32 AM

I would use an inbound email service to do this.

Your apex could would then process each email that comes in.  

There are 2 types of attachments that can be accessed from the inbound email, textAttachments and binaryAttachments.

they are passed in as arrays of objects.

Your code would loop through each type of attachment you are interested and process the individual results.

For example, you could restrict your inbound service to only accept binary attachments (like PDF's, Spreadsheets, etc).

Then you would loop through the array of binaryAttachments, and extract each one, possibly saving it is a document, by converting the body (a blob) into a document object, and then saving that document in a specified folder.

Look in the documenation for Inbound email service, and for Inboundemail.binaryattachment for more details.


Here are links to some documentation around Email Services, including sample code processing an Inbound Email:


Force.com Email Services

Apex Inbound Email Class documentation






I have written an Apex class which implements the handleInboundEmail method of Messaging.InboundEmailHandler.


How to invoke this Apex class when ever the salesforce receives a mail


The purpose of the above Apex class is process all the mails that come to salesforce.

I want to get the attachments of the email then I want to insert the attachment into an Opportunity


Here is the code what Iam doing

Any help on this is greatly is appreciated



global class myEmailHandler implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, 
                                                       Messaging.InboundEnvelope env){
  // Create an inboundEmailResult object for returning the result of the Apex Email Service
  Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
  String myPlainText= '';
  String sub= '';
  String attachmentName= '';
  String body= '';
  // Add the email plain text into the local variable  
  //myPlainText = email.plainTextBody;
  //sub = email.subject;
  //Messaging.InboundEmail.TextAttachment[]   tAttachments = email.textAttachments;
  Messaging.InboundEmail.BinaryAttachment[] bAttachments = email.binaryAttachments;

  if (tAttachments != null)
        for (Messaging.InboundEmail.TextAttachment mailAttachment : tAttachments)
            attachmentName = mailAttachment.fileName;
            body = mailAttachment.body;
   Opportunity opp = [select id from opportunity where name = 'HSBC' limit 1];
   if (bAttachments != null)
          for (Messaging.InboundEmail.BinaryAttachment mailAttachment : bAttachments)
                String attachmentName   = mailAttachment.fileName;
                Blob   body             = mailAttachment.body;
                Attachment attachment   = new Attachment ();
                // check attachment name if null                        
                if(attachmentName == null || attachmentName == '' )
                    attachmentName = 'noname';              
                attachment.name = attachmentName;
                attachment.body = body;
                attachment.parentId = opp.id;


 try {  
     System.debug('PlainText of the email is..... ' + myPlainText);
     System.debug('Subject of the email is..... ' + sub);
     System.debug('body of the email  attachment is..... ' + body);
     System.debug('attachment name of the email is..... ' + attachmentName);

  // The exception is written to the Apex debug log.
 catch (Exception e) {
      System.debug('Exception is.....  ' + e);
 // Return the result for the Apex Email Service
    return result;
  } // end of method handleInboundEmail
   static testMethod void testCases() {

   // Create a new email and envelope object
   Messaging.InboundEmail email = new Messaging.InboundEmail();
   Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

   // Create the plainTextBody and fromAddres for the test
   email.plainTextBody = 'Hi Suhel I have gone through the Force.com Apex code Language Reference';
   email.fromAddress = 'varansunil@gmail.com';
   email.subject = 'status on stripping the attachment with email';
   //create an attachment
   Messaging.InboundEmail.TextAttachment inbTextAttchment = new Messaging.InboundEmail.TextAttachment();
   inbTextAttchment.body = 'Test Test Test Test Test Test Test Test Test';
   inbTextAttchment.fileName = 'myAttachment.txt';
   Messaging.InboundEmail.TextAttachment[] textAttachs = new Messaging.InboundEmail.TextAttachment[1];
   textAttachs[0] = inbTextAttchment;   
   email.textAttachments = textAttachs;   
   myEmailHandler caseObj = new myEmailHandler();
   caseObj.handleInboundEmail(email, env);
 } // end of class myEmailHandler








Looks like you are pretty close.  The only major thing missing is you never inserted the attachment.

A few more lines in this section would do it:


attachment.name = attachmentName; attachment.body = body; attachment.parentId = opp.id; try{ insert attachment; }catch(DMLException e){ system.debug('ERROR Inserting attachment:'+e.getDMLMessage(0)); }


 You might also want to include the ContentType as well, so it is easier for users to open the attachments you add to the opportunity.




Thanks Rae!


your code is helpful and I got it









I have the similar problem. I want to related attachment's parentId to case in place of InboundEmaiResult. Also attached the code for reference. It is working fine if I test it using testmethod but when I try to execute it by sending manual mail it fails. Please guide.



global class EmailToCase implements Messaging.Inboundemailhandler { global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,Messaging.InboundEnvelope env){ Case caseObj = new Case(); caseObj.Description = email.htmlBody; caseObj.Priority = 'Medium'; caseObj.Origin = 'Email'; caseObj.Subject = email.subject; caseObj.SuppliedEmail = email.fromAddress; try { insert caseObj; }catch(QueryException e) { System.debug(e); } System.debug(caseObj); List<Attachment> attachObjList = new List<Attachment> (); if(email.binaryAttachments != null && email.binaryAttachments.size() > 0) { for(Messaging.InboundEmail.BinaryAttachment binaryAttachObj : email.binaryAttachments) { Attachment attachmentObj = new Attachment(); attachmentObj.Body = binaryAttachObj.body; //attachmentObj.ContentType = binaryAttachObj.mimeTypeSubType; attachmentObj.Name = binaryAttachObj.fileName; attachmentObj.ParentId = caseObj.Id; attachObjList.add(attachmentObj); } } if(email.textAttachments != null && email.textAttachments.size() > 0) { for(Messaging.InboundEmail.Textattachment textAttachObj : email.textAttachments) { Attachment attachmentObj = new Attachment(); attachmentObj.Body = Blob.valueOf(textAttachObj.body); //attachmentObj.ContentType = textAttachObj.mimeTypeSubType; attachmentObj.Name = textAttachObj.fileName; attachmentObj.ParentId = caseObj.Id; attachObjList.add(attachmentObj); } } try { insert attachObjList; }catch(QueryException e) { System.debug('Attachment Error ' + e); } System.debug(attachObjList); return null; } }

 Test Method



// Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); Messaging.InboundEmail.BinaryAttachment inAtt = new Messaging.InboundEmail.BinaryAttachment(); email.subject = 'test'; env.fromAddress = 'user@acme.com'; // set the body of the attachment inAtt.body = blob.valueOf('test'); inAtt.fileName = 'my attachment name'; inAtt.mimeTypeSubType = 'plain/txt'; email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] {inAtt }; // call the class and test it with the data in the testMethod EmailToCase emailServiceObj = new EmailToCase(); emailServiceObj.handleInboundEmail(email, env );