Having an issue pulling an Inbound Email's attachments and saving it to a Task

All we need is an easy explanation of the problem, so here it is.

I’m working with a new custom inbound email service, and in my testing I’m managing to pull all the necessary information to the task I’m creating for it, but for some reason the attachments aren’t coming with. If anyone has any insight it would be appreciated. I already check to ensure that the settings for the service is set to accept all attachments, so it shouldn’t be blocking anything. This is the handler that I have so far:

global class AA_InboundEmailHandler implements Messaging.InboundEmailHandler{

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope){

    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    String sbj = email.subject;
    sbj = sbj.substringAfterLast('-').trim();
    try{
        result = createTask(sbj, email);
        }
    catch(exception e){
        system.debug('Unexpected Object Type');
        result.success = false;
        }
        return result;
    }

public static Messaging.InboundEmailResult createTask(string sbj, Messaging.InboundEmail email){
    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    string name;
    sObject r;
    ID ownerID;
    try{
        if(sbj.startsWith('001')){
            Account a = new Account();
            a = [SELECT ID, OwnerID, Name FROM Account WHERE ID =: sbj];
            r = a;
            name = a.Name;
            ownerID = a.OwnerID;
            }
        //Contact   
        else if(sbj.startsWith('003')){
            Contact a = new Contact();
            a = [SELECT ID, OwnerID, Name FROM Contact WHERE ID =: sbj];
            r = a;
            name = a.Name;
            ownerID = a.OwnerID;
            }
        //Lead  
        else if(sbj.startsWith('00Q')){
            Lead a = new Lead();
            a = [SELECT ID, OwnerID, Name FROM Lead WHERE ID =: sbj];
            r = a;
            name = a.Name;
            ownerID = a.OwnerID;
            }
        //Opportunity   
        else if(sbj.startsWith('006')){
            Opportunity a = new Opportunity();
            a = [SELECT ID, OwnerID, Name FROM Opportunity WHERE ID =: sbj];
            r = a;
            name = a.Name;
            ownerID = a.OwnerID;
            }

        // Turn email body into note
        Task task = new Task(ActivityDate = Date.today(),
                            CallDisposition = 'Email Received from Client',
                            CallType = 'Inbound',
                            Description = email.plainTextBody,
                            Status = 'Completed',
                            Subject = 'Email from: ' + email.fromAddress,
                            Type = 'Email',
                            WhatId = r.Id);

                            if(sbj.startsWith('001')){
                                task.Account__c = r.Id;
                                }
                            //Contact   
                            else if(sbj.startsWith('003')){
                                task.Contact__c = r.Id;
                                }
                            //Lead  
                            else if(sbj.startsWith('00Q')){
                                task.Lead__c = r.Id;
                                }
                            //Opportunity   
                            else if(sbj.startsWith('006')){
                                task.Opportunity__c = r.Id;
                                }
            insert task;

        Task newTask = new Task(Description =  email.htmlBody,
                                Priority = 'Normal',
                                Status = 'New Email received for ' + name,
                                Subject = email.subject,
                                IsReminderSet = TRUE,
                                WhatId = r.Id,
                                Type = 'Email',
                                ReminderDateTime = System.now()+1,
                                OwnerId = ownerID);
        // Insert the new Task
        insert newTask; 
        // Save attachments, if any
        for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {

            Attachment attachment = new Attachment();
            attachment.Name = tAttachment.fileName;
            attachment.Body = Blob.valueOf(tAttachment.body);
            attachment.ParentId = task.Id;
            insert attachment;
            }

            //Save any Binary Attachment

            for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
            Attachment attachment = new Attachment();
            attachment.Name = bAttachment.fileName;
            attachment.Body = bAttachment.body;
            attachment.ParentId = task.Id;
            insert attachment;
            }
            result.success = true;
            }
    catch(Exception E){
        result.success = false;
        }   
    return result;
    }

}

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Not that anyone seemed too interested, but the fault was the result of the in-context user being different than that of the Task owner I was attaching the processed files to. System didn’t like that, but it wasn’t clear until some further digging. Anyway, here’s the final result without issue in case it helps someone in the future:

global class AA_InboundEmailHandler implements Messaging.InboundEmailHandler{

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope){

    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    String sbj = email.subject;
    sbj = sbj.substringAfterLast('-').trim();
    try{
        result = createTask(sbj, email);
        }
    catch(exception e){
        system.debug('Unexpected Object Type');
        result.success = false;
        }
        return result;
    }

public static Messaging.InboundEmailResult createTask(string sbj, Messaging.InboundEmail email){
    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    string name;
    sObject r;
    ID ownerID;
    Task newTask;
    try{
        if(sbj.startsWith('001')){
            Account a = new Account();
            a = [SELECT ID, OwnerID, Name FROM Account WHERE ID =: sbj];
            r = a;
            name = a.Name;
            ownerID = a.OwnerID;
            }
        //Contact   
        else if(sbj.startsWith('003')){
            Contact a = new Contact();
            a = [SELECT ID, OwnerID, Name FROM Contact WHERE ID =: sbj];
            r = a;
            name = a.Name;
            ownerID = a.OwnerID;
            }
        //Lead  
        else if(sbj.startsWith('00Q')){
            Lead a = new Lead();
            a = [SELECT ID, OwnerID, Name FROM Lead WHERE ID =: sbj];
            r = a;
            name = a.Name;
            ownerID = a.OwnerID;
            }
        //Opportunity   
        else if(sbj.startsWith('006')){
            Opportunity a = new Opportunity();
            a = [SELECT ID, OwnerID, Name FROM Opportunity WHERE ID =: sbj];
            r = a;
            name = a.Name;
            ownerID = a.OwnerID;
            }

        newTask = new Task(Description =  email.htmlBody,
                                Priority = 'Normal',
                                Status = 'New Email received for ' + name,
                                Subject = email.subject,
                                IsReminderSet = TRUE,
                                WhatId = r.Id,
                                Type = 'Email',
                                ReminderDateTime = System.now()+1,
                                OwnerId = ownerID);
                                if(sbj.startsWith('001')){
                                    newTask.Account__c = r.Id;
                                    }
                                //Contact   
                                else if(sbj.startsWith('003')){
                                    newTask.Contact__c = r.Id;
                                    }
                                //Lead  
                                else if(sbj.startsWith('00Q')){
                                    newTask.Lead__c = r.Id;
                                    }
                                //Opportunity   
                                else if(sbj.startsWith('006')){
                                    newTask.Opportunity__c = r.Id;
                                    }

            // Insert the new Task
            insert newTask;
            // Save attachments, if any
        list<Attachment> attachList = new list<Attachment>();
        if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
            for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
                Attachment attachment = new Attachment();
                // attach to the newly created contact record
                attachment.ParentId = newTask.Id;
                attachment.Name = email.binaryAttachments[i].filename;
                attachment.Body = email.binaryAttachments[i].body;
                attachment.OwnerID = ownerID;
                attachList.add(attachment);
                }
            }

          if (email.textAttachments != null && email.textAttachments.size() > 0) {
            for (integer i = 0 ; i < email.textAttachments.size() ; i++) {
                Attachment attachment = new Attachment();
                // attach to the newly created contact record
                attachment.ParentId = newTask.Id;
                attachment.Name = email.textAttachments[i].filename;
                attachment.Body = blob.valueOf(email.textAttachments[i].body);
                attachment.OwnerID = ownerID;
                attachList.add(attachment);
                }
            }

            if(!attachList.isEmpty()){
                insert attachList;
                }
            result.success = true;

        }
    catch(Exception E){
        result.success = false;
        }
    return result;
    }

}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply