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
llisallisa 

How to write a test class for Email inbound?

Hello,

I an a new learner to Email Inbound class.So please Help me on this code.

global class RebateMailService implements Messaging.InboundEmailHandler{
public SMS_bit_A__c bitA; 
 public List<Attachment> attachments;

  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        String bitAName,comments,status;
       
        
        String[] subjectSplit=email.Subject.split(' ');
            if(!subjectSplit.isEmpty()){
                bitAName=subjectSplit[subjectSplit.size()-2];
                status=subjectSplit[subjectSplit.size()-1];
            }
            
        String[] bodySplit= email.plainTextBody.split('\n');
            if(!bodySplit.isEmpty()){
                   comments=bodySplit[0];
            }    
        bitA=[select id,name,SMS_Contact_Email__c,SMS_Status__c,SMS_VP_sales_email__c,SMS_Legal_person_email__c,Owner.Name from SMS_bit_A__c where name=:bitAName Limit 1];
        attachments=[select id,name,Body,CreatedDate from Attachment where parentId=: bitA.Id Order By CreatedDate Desc LIMIT 1];
        
        if(bitA!=null){           
        if(bitA.SMS_Status__c.equalsIgnoreCase('Draft') || bitA.SMS_Status__c.equalsIgnoreCase('Customer Reject') 
            || bitA.SMS_Status__c.equalsIgnoreCase('In Process')){
            Customer_Email__c custEmail=new Customer_Email__c();
            custEmail.Name=email.Subject;
            custEmail.Email_Content__c=email.htmlBody;
            custEmail.From__c=email.fromAddress;
            custEmail.bit_A__c=bitA.Id;
            insert custEmail;
            if (email.binaryAttachments !=null && email.binaryAttachments.size() > 0)
            {
                for (integer i = 0 ; i < email.binaryAttachments.size() ; i++)
                {
                    Attachment a = new Attachment(ParentId = custEmail.Id,
                    Name = email.binaryAttachments[i].filename,
                    Body = email.binaryAttachments[i].body);
                    insert a;
                }
            }
            
            if(email.textAttachments!=null && email.textAttachments.size() > 0)
            {
                for (integer i = 0 ; i < email.textAttachments.size() ; i++)
                {
                    Attachment a = new Attachment(ParentId = custEmail.Id,
                    Name = email.textAttachments[i].filename,
                    Body = Blob.valueOf(email.textAttachments[i].body));
                    insert a;
                }
            }   
    }
    }
    return result;
 }   
    void sendEmailtoNextApproverfinal(String sendTo){
        List<String> sendToAdds=new List<String>();
        sendToAdds.add(sendTo);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(sendToAdds);
        
        mail.setReplyTo('noreply@salesforce.com');
        mail.setSenderDisplayName(bitA.Owner.Name);
        //List<String> ccTo = new List<String>();
        //mail.setCcAddresses(ccTo);
        String subject = 'Final Rebate Program ' + bitA.name;
        mail.setSubject(subject);
        String body = getEmailrebateprogram(subject);
        mail.setHtmlBody(body);
         // Create the email attachment
        if(attachments.size()>0){
        Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
        efa1.setFileName(attachments[0].name);
        efa1.setBody(attachments[0].Body);
        mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa1});
        }
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
    
    String getEmailrebateprogram(String subject){
        String strBody = '';        
        strBody+='Dear Customer.';
        strBody+='<BR/>';
        strBody+='<BR/>';
        strBody+= 'This is our Rebate';
        strBody+='<BR/>';
        strBody+='<BR/>';
        strBody+= 'Find the attachment below ';
        strBody+='<BR/>';
        strBody+='<BR/>';
        strBody+='Regards,';
        strBody+='<BR/>';
        strBody+='<BR/>';
        strBody+='abc Solutions, Inc.';
        strBody+='<BR/>';
        strBody+=' Security Division';
        strBody+='<BR/>';
        strBody+='<BR/>';
        strBody+='<BR/>';
        strBody+='Thanks ';
return strBody;    
    } 
    
}
Abhishek BansalAbhishek Bansal
Hi,

Plesae try with below test class :
//Test Method for main class
   
   static testMethod void TestinBoundEmail()
   {
       // create a new email and envelope object
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
       
       // setup the data for the email
      email.subject = 'Create Draft';
      email.fromAddress = 'someaddress@email.com';
      email.plainTextBody = 'email body\n2225256325\nTitle';
      
      SMS_bit_A__c testSMS = new SMS_bit_A__c(Name = 'Create');
      insert testSMS;
      
      // add an Binary attachment
      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfileone.txt';
      attachment.mimeTypeSubType = 'text/plain';
      attachment.ParentId = testSMS.id;
      email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
      
      
  
      // add an Text atatchment
  
      Messaging.InboundEmail.TextAttachment attachmenttext = new Messaging.InboundEmail.TextAttachment();
      attachmenttext.body = 'my attachment text';
      attachmenttext.fileName = 'textfiletwo3.txt';
      attachmenttext.mimeTypeSubType = 'texttwo/plain';
      attachment.ParentId = testSMS.id;
      email.textAttachments =   new Messaging.inboundEmail.TextAttachment[] { attachmenttext };
      
      
      // call the email service class and test it with the data in the testMethod
      RebateMailService  testInbound=new RebateMailService();
   
   }

Let me know if you have any issue.

Thanks,
Abhishek
llisallisa
Hi Abhishek, thanks for your reply.
It gives me an error "Variable does not exist: ParentId".
By  ignoring ParentId it is giving 0% code coverage.
Abhishek BansalAbhishek Bansal
Hi Monalisa.

Please try with below test class :
//Test Method for main class
   
   static testMethod void TestinBoundEmail()
   {
       // create a new email and envelope object
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
       
       // setup the data for the email
      email.subject = 'Create Draft';
      email.fromAddress = 'someaddress@email.com';
      email.plainTextBody = 'email body\n2225256325\nTitle';
      
      // add an Binary attachment
      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfileone.txt';
      attachment.mimeTypeSubType = 'text/plain';
      attachment.ParentId = testSMS.id;
      email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
      
      
  
      // add an Text atatchment
  
      Messaging.InboundEmail.TextAttachment attachmenttext = new Messaging.InboundEmail.TextAttachment();
      attachmenttext.body = 'my attachment text';
      attachmenttext.fileName = 'textfiletwo3.txt';
      attachmenttext.mimeTypeSubType = 'texttwo/plain';
      attachment.ParentId = testSMS.id;
      email.textAttachments =   new Messaging.inboundEmail.TextAttachment[] { attachmenttext };
      
      SMS_bit_A__c testSMS = new SMS_bit_A__c(Name = 'Create');
      insert testSMS;
      
      Attachment testAttach = new Attachment();
      testAttach.ParentId = testSMS.Id;
      //Please add any required field if you get error
      insert testAttach;
      
      // call the email service class and test it with the data in the testMethod
      RebateMailService  testInbound=new RebateMailService(email, env);
   
   }

Thanks,
Abhishek
llisallisa
Variable does not exist: testSMS.id error message.
llisallisa
Sorry previous error msg comes wrongly.

But still  is is giving the error "Variable does not exist: ParentId"
Abhishek BansalAbhishek Bansal
Leave that attachment part and try without it
llisallisa
Hi, i tried that one too,it is giving 0% code coverage
llisallisa
Hi i this test class only give 14% of code coverage.it is not covering the attachment part.

@isTest(seeAllData=true)
private class test_RebateMailService {
   //Test Method for main class
  static testMethod void TestinBoundEmail()
   {
       // create a new email and envelope object
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
       
       // setup the data for the email
      email.subject = 'Create Contact';
      email.fromAddress = 'someaddress@email.com';
      email.plainTextBody = 'email body\n2225256325\nTitle';
      
      // add an Binary attachment
      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfileone.txt';
      attachment.mimeTypeSubType = 'text/plain';
      email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
      
      
  
      // add an Text atatchment
  
      Messaging.InboundEmail.TextAttachment attachmenttext = new Messaging.InboundEmail.TextAttachment();
      attachmenttext.body = 'my attachment text';
      attachmenttext.fileName = 'textfiletwo3.txt';
      attachmenttext.mimeTypeSubType = 'texttwo/plain';
      email.textAttachments =   new Messaging.inboundEmail.TextAttachment[] { attachmenttext };
      
      
      // call the email service class and test it with the data in the testMethod
      RebateMailService  testInbound=new RebateMailService ();
      testInbound.handleInboundEmail(email, env);
      
   }    
}