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
Sandeep TechAffinitySandeep TechAffinity 

Test Class for Inbound Email service with attachments?

Hi Guys,

I have created an Inbound Email service. But I am not sure how to create a Test class. Help me.
 
global class captureEmailResponses implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        String Activityname = email.fromname;
        String fromemailaddresss = email.fromAddress;
        String des = email.plainTextBody;
        String tasksubject = email.subject;
        try {
            system.debug('Reply To '+email.inReplyTo);
            EmailMessage originalMessage = [SELECT ReplyToEmailMessageId, MessageIdentifier, ThreadIdentifier, CreatedById, ActivityId FROM EmailMessage WHERE MessageIdentifier = :email.inReplyTo LIMIT 1];

            Task linkedTask = [SELECT Id, WhoId FROM Task WHERE Id = :originalMessage.ActivityId LIMIT 1];

            Lead lead = [SELECT Id, Name, Email, ShareGroupId__c, LastModifiedById, Status
                         FROM Lead
                         WHERE Id = :linkedTask.WhoId
                         LIMIT 1];
            User lastUser = [SELECT Id, Email
                             FROM User
                             WHERE Id = :originalMessage.CreatedById
                             LIMIT 1];
            EmailMessage[] newEmail = new EmailMessage[0];
            String[] toUsers = new String[]{lead.LastModifiedById};
                newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
                                              FromName = email.fromName,
                                              Incoming = True,
                                              ToAddress = lastUser.Email,
                                              //ToAddress = email.toAddresses[0],
                                              Subject = email.subject,
                                              //RelatedToId = lead.Id, // This throws error about not the expected type???
                                              TextBody = email.plainTextBody,
                                              HtmlBody = email.htmlBody,
                                              MessageIdentifier = email.messageId,
                                              ReplyToEmailMessageId = originalMessage.Id,
                                              ThreadIdentifier = originalMessage.ThreadIdentifier,
                                              Status = '3')); // Sets to replied.
            
            insert newEmail;

            EmailMessageRelation emr = new EmailMessageRelation();
            emr.emailMessageId = newEmail[0].Id;
            emr.relationAddress = email.fromAddress;
            emr.relationId = lead.id; // Lead Id
            emr.relationType = 'FromAddress';
            insert emr;
            
            EmailMessageRelation toEmr = new EmailMessageRelation();
            toEmr.emailMessageId = newEmail[0].Id;
            toEmr.relationAddress = lastUser.Email;
            toEmr.relationId = lastUser.Id; // User Id
            toEmr.relationType = 'ToAddress';
            insert toEmr;
            
            lead.status = 'Patient Replied';
            update lead;
            
            if(email.textAttachments != null)
            {
                system.debug('email.textAttachments '+ email.textAttachments);

                for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                    Attachment attachment = new Attachment();
                    
                    attachment.Name = tAttachment.fileName;
                    attachment.Body = Blob.valueOf(tAttachment.body);
                    attachment.ParentId = lead.Id;
                    insert attachment;
                }
            }
            if(email.binaryAttachments != null && email.binaryAttachments.size() > 0){
                for(Messaging.InboundEmail.BinaryAttachment att : email.binaryAttachments){
                    system.debug('attachmentsList -> '+email.binaryAttachments);
                }
                List<ContentVersion>cvList = new List<ContentVersion>();
                List<ContentDocumentLink> cdlList = new List<ContentDocumentLink>();
                for (Messaging.InboundEmail.BinaryAttachment binAttach : email.binaryAttachments) {
                    system.debug('@@@ binAttach.fileName '+binAttach.fileName);
                    system.debug('@@@ binAttach.fileName '+binAttach.body);
                    system.debug('@@@ binAttach.fileName '+binAttach.fileName);
                    
                    ContentVersion testContentInsert = new ContentVersion();
                    testContentInsert.Title = binAttach.fileName;
                    testContentInsert.VersionData = binAttach.body;
                    testContentInsert.PathOnClient = '/' + binAttach.fileName ;
                    cvList.add(testContentInsert);
                    
                }
                insert cvList;
                cvList = [select id, ContentDocumentId from ContentVersion WHERE Id in :cvList];
                for (ContentVersion cv : cvList) {
                    ContentDocumentLink cl = new ContentDocumentLink();
                    cl.ContentDocumentId = cv.ContentDocumentId;
                    cl.LinkedEntityId = lead.id; //Shared with record ID
                    cl.ShareType = 'I';
                    cl.Visibility = 'AllUsers';
                    cdlList.add(cl);

                }
                insert cdlList;
  
            }else{
                system.debug('attachmentsList -> '+email.binaryAttachments);
            }
            
        }

        catch (QueryException e) {
            System.debug('Query Issue: ' + e);
            System.debug('Query Issue: ' + e.getLineNumber());
            System.debug('Query Issue: ' + e.getCause());
            System.debug('Query Issue: ' + e.getTypeName());
            System.debug('Query Issue: ' + e.getMessage());
        }
        result.success = true;
        return result;
    }
}




Thank You
Sandeep
SwethaSwetha (Salesforce Developers) 
HI Sandeep,
These related posts should help you get started
https://developer.salesforce.com/forums/?id=9060G000000MQTIQA4
http://sfdcfaq.blogspot.com/2013/04/test-class-for-email-service-using-apex.html
https://developer.salesforce.com/forums/?id=9062I000000Bm1LQAS

Happy to take any follow-up queries. Please add where specifically you are stuck.Thanks
Sandeep TechAffinitySandeep TechAffinity
Hi Swetha,

Thank you very much for your response. I have gone through all the links but still not completed my task due to these lines of code is not getting covered. Can you help me?
 
EmailMessage originalMessage = [SELECT ReplyToEmailMessageId, MessageIdentifier, ThreadIdentifier, CreatedById, ActivityId FROM EmailMessage WHERE MessageIdentifier = :email.inReplyTo LIMIT 1];

            Task linkedTask = [SELECT Id, WhoId FROM Task WHERE Id = :originalMessage.ActivityId LIMIT 1];

            Lead lead = [SELECT Id, Name, Email, ShareGroupId__c, LastModifiedById, Status
                         FROM Lead
                         WHERE Id = :linkedTask.WhoId
                         LIMIT 1];
            User lastUser = [SELECT Id, Email
                             FROM User
                             WHERE Id = :originalMessage.CreatedById
                             LIMIT 1];
            EmailMessage[] newEmail = new EmailMessage[0];
            String[] toUsers = new String[]{lead.LastModifiedById};
                newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
                                              FromName = email.fromName,
                                              Incoming = True,
                                              ToAddress = lastUser.Email,
                                              //ToAddress = email.toAddresses[0],
                                              Subject = email.subject,
                                              //RelatedToId = lead.Id, // This throws error about not the expected type???
                                              TextBody = email.plainTextBody,
                                              HtmlBody = email.htmlBody,
                                              MessageIdentifier = email.messageId,
                                              ReplyToEmailMessageId = originalMessage.Id,
                                              ThreadIdentifier = originalMessage.ThreadIdentifier,
                                              Status = '3')); // Sets to replied.
            
            insert newEmail;

            EmailMessageRelation emr = new EmailMessageRelation();
            emr.emailMessageId = newEmail[0].Id;
            emr.relationAddress = email.fromAddress;
            emr.relationId = lead.id; // Lead Id
            emr.relationType = 'FromAddress';
            insert emr;
            
            EmailMessageRelation toEmr = new EmailMessageRelation();
            toEmr.emailMessageId = newEmail[0].Id;
            toEmr.relationAddress = lastUser.Email;
            toEmr.relationId = lastUser.Id; // User Id
            toEmr.relationType = 'ToAddress';
            insert toEmr;
            
            lead.status = 'Patient Replied';
            update lead;

Thank you
Sandeep​​​​​​​