[SalesForce] Email Service: Attempt to de-reference a null object

I have created a Email service which saves attachments into opportunites, when sending emails an error message is returned back to the mailbox stating that it has failed processing because Attempt to de-reference a null object.

It says the error occured in line the where the for loop is started (line 4).

Here is the code:

global class myHandler implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
....
    // Save binary attachments, if any
    for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
      Attachment attachment = new Attachment();

      attachment.Name = bAttachment.fileName;
      attachment.Body = bAttachment.body;
      attachment.ParentId = matcher.group(0);
      insert attachment;
    }

EDIT

Created new code to check first if there are any uploads…

if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
    for (integer i = 0 ; i < email.binaryAttachments.size() ; i++)
    {          
      Attachment attachment = new Attachment();
      attachment.Name = email.binaryAttachments[i].filename;
      attachment.Body = email.binaryAttachments[i].body;
      attachment.ParentId = matcher.group(0);
      insert attachment;          
    }
}

It does not return any errors when saving however it does not save the attachments either.

Best Answer

Based on my experience, the error is not caused by the code you pasted. Since this error happened at the for (...) line, I would say most probably the object email is null. Hence when you try to retrieve email.binaryAttachments, the error occurs. You can probably debug from this.

Related Topic