function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Andrew AldisAndrew Aldis 

Add attachment to a task with Inbound Email Handler

I am creating a inbound email handler class to create a task when an email is recieved.  I would like any attachment to be added to the task as well but cannot seem to get that part to work.  The class will create a task correclty it just won't create the attachment.  My code is below.

global class partnerTaskEmailClass implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope){                
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();        
        Contact Contact;

        if([select count() from Contact where Email = :email.fromAddress ] == 0)
            Contact = [Select ID, Account_Id__c from Contact where email = '' AND Account_Id__c = '0018000001BeR5A' limit 1];
        else {
            Contact = [Select ID, Account_Id__c from Contact where email = :email.fromAddress ];
            task t = new task();
            t.WhoId = Contact.Id;
            t.whatId = Contact.Account_Id__c;
            t.Subject = email.subject;
            t.description = email.PlainTextBody;
            t.Partner_Email_Address__c  = email.fromAddress;
            t.Type = 'Partner Request';
            t.ActivityDate =;
            t.RecordTypeId = '0121b000000CkAG';
            t.OwnerId = '00580000004V5YW';
            t.Priority = 'Normal';
            insert t;
            if(email.textAttachments != null)
                Task newtask = [Select Id from Task where Subject = : email.subject order by CreatedDate Desc Limit 1];
                for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                  Attachment attachment = new Attachment();
                  attachment.Name = tAttachment.fileName;
                  attachment.Body = Blob.valueOf(tAttachment.body);
                  attachment.ParentId = newtask.Id;
                  insert attachment;

Return Result;

Since you are querying the task record based on the subject field there might be different tasks with the same task subject in your org, so attachments might associate with that records.

1. Can you do the global search in your org with attachment name to identify whether it is inserted or not ?
2. If the attachment is associated with a different task then change the SOQL query. Instead of filtering with the task subject, use Id field
Andrew AldisAndrew Aldis
No, they just aren't getting inserted.  No attachments have been added to anything since I began testing this code.