Handling inbound email attachment and attaching the attachment in chatter post

Let’s take a scenario where the following sample code will be applicable.

There is a WorkItem__c object. When an email will be sent mentioning the WorkItem number e.g. WI-0001, our code will read the attachment and attach it at the chatter post of the record i.e. WI-0001. The First and Second officer will also be mentioned in the post.

global class InboundWorkItemEmailHandler implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        System.debug('New email with subject @@@@ ' + email.subject);
        Messaging.InboundEmailResult result  = new Messaging.InboundEmailresult();
        String strEmailSubject               = email.subject;
        List<String> lstEmailSubjectSplitted = new List<String>();
        String workItemNumber;
        
        if (strEmailSubject != null) {
            lstEmailSubjectSplitted = strEmailSubject.split(' ');
            if (!lstEmailSubjectSplitted.isEmpty()) {
                for (String str : lstEmailSubjectSplitted) {
                    if (str.contains('WI-')) {
                        workItemNumber = str;
                    }
                }
            }
        }
        
        if (workItemNumber != null) {
            List<WorkItem__c> lstWorkItem = [SELECT Id, Name, FirstOfficer__c, SecondOfficer__c
                                             FROM   WorkItem__c
                                             WHERE  Name = :workItemNumber];
            if (!lstWorkItem.isEmpty()) {
                ContentVersion cVersion;
                ContentDocumentLink cDocLink;
                
                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
                    
                    cVersion                     = new ContentVersion();
                    cVersion.ContentLocation     = 'S';
                    cVersion.PathOnClient        = email.binaryAttachments[0].fileName;
                    cVersion.Origin              = 'H';
                    cVersion.Title               = email.binaryAttachments[0].fileName;
                    cVersion.VersionData         = email.binaryAttachments[0].body;
                    Insert cVersion;
                    
                    Id conDocumentId             = [SELECT ContentDocumentId
                                                    FROM   ContentVersion 
                                                    WHERE  Id = :cVersion.Id].ContentDocumentId;
                    
                    if (cVersion != null) {
                        createChatterPost(lstWorkItem[0], conDocumentId);
                    }
                }
                
            }
        }
        
        return result;
    }
    
    public void createChatterPost(WorkItem__c workItem, Id conDocumentId) {
        
        List<ConnectApi.BatchInput> batchInputs             = new List<ConnectApi.BatchInput>();
        ConnectApi.FeedItemInput feedItemInput              = new ConnectApi.FeedItemInput();
        ConnectApi.MentionSegmentInput mentionSegmentInput1 = new ConnectApi.MentionSegmentInput();
        ConnectApi.MentionSegmentInput mentionSegmentInput2 = new ConnectApi.MentionSegmentInput();
        ConnectApi.MessageBodyInput messageBodyInput        = new ConnectApi.MessageBodyInput();
        ConnectApi.TextSegmentInput textSegmentInput        = new ConnectApi.TextSegmentInput();
        
        messageBodyInput.messageSegments                    = new List<ConnectApi.MessageSegmentInput>();
        
        if (workItem.FirstOfficer__c != null) {
            mentionSegmentInput1.id                         = workItem.FirstOfficer__c;//Mention user here
            messageBodyInput.messageSegments.add(mentionSegmentInput1);
        }
        if (workItem.SecondOfficer__c != null) {
            mentionSegmentInput2.id                         = workItem.SecondOfficer__c;//Mention user here
            messageBodyInput.messageSegments.add(mentionSegmentInput2);
        }
        
        textSegmentInput.text                               = '\n' + ' ' + Label.NewAttachmentAvailable;
        messageBodyInput.messageSegments.add(textSegmentInput);
        
        feedItemInput.body                                  = messageBodyInput;
        feedItemInput.feedElementType                       = ConnectApi.FeedElementType.FeedItem;
        feedItemInput.subjectId                             = workItem.Id;
        
        feedItemInput.capabilities                          = new ConnectAPI.FeedElementCapabilitiesInput();
        feedItemInput.capabilities.files                    = new ConnectAPI.FilesCapabilityInput();
        feedItemInput.capabilities.files.items              = new List<ConnectAPI.FileIdInput>();
        ConnectAPI.FileIdInput attachFile                   = new ConnectAPI.FileIDInput();
        attachFile.Id                                       = conDocumentId;
        feedItemInput.capabilities.files.items.add(attachFile);
        
        
        ConnectApi.BatchInput batchInput                    = new ConnectApi.BatchInput(feedItemInput);
        batchInputs.add(batchInput);
        
        ConnectApi.ChatterFeeds.postFeedElementBatch(Network.getNetworkId(), batchInputs);
    }
}

Test class for the above class

@isTest
public class TestDataFactory {
    
    public static WorkItem__c createWorkItem(Boolean doInsert) {
        WorkItem__c workItem = new WorkItem__c();
        
        if (doInsert) {
            insert workItem;
        }
        
        return workItem;
    }

}
@isTest (SeeAllData = false)
public class InboundApplicationEmailHandlerTEST {
    @TestSetup 
    static void TestData() {
        WorkItem__c workItem = TestDataFactory.createWorkItem(true);
    }
    
    static testmethod void handleInboundEmailTest(){
        List<WorkItem__c> lstWorkItem = [SELECT Id, Name
                                         FROM   WorkItem__c];
        
        
        Messaging.InboundEmail.BinaryAttachment inboundAttachment = new Messaging.InboundEmail.BinaryAttachment();
        inboundAttachment.body                                    = blob.valueOf('Test');
        inboundAttachment.fileName                                = 'Email_Attachment.txt';
        inboundAttachment.mimeTypeSubType                         = 'text/plain';
        
        Messaging.InboundEmail email                              = new Messaging.InboundEmail();
        email.subject                                             = lstWorkItem[0].Name;
        email.binaryAttachments                                   = new Messaging.inboundEmail.BinaryAttachment[] {inboundAttachment};
            
        Messaging.InboundEnvelope envelope                        = new Messaging.InboundEnvelope();
        
        
        Test.startTest();
        InboundApplicationEmailHandler emailHanderService = new InboundApplicationEmailHandler();
        Messaging.InboundEmailResult result               = emailHanderService.handleInboundEmail(email, envelope);
        Test.stopTest();        
    }
}