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
Chris LamChris Lam 

Unable to perform Regex Match in my Email to Object Apex class

Hi Everyone,

I am trying to create an Apex class which will add the incoming email message which contains projectID in the subject heading into an existing project(custom objec) and discard the email message if it doesn't match any of our project ID.

The test class works fine but is not able to trigger the true condition for the below IF statement even though  the System.debug(myMatcher.group()); contains a valid Name in the project__c database.

IF ([SELECT COUNT() FROM project__c WHERE Name =:myMatcher.group()] == 1)

I have ran a similar Apex code as below below using developer console (Open Execute Anonymous Window) and the three system debugs are returning TRUE result of the IF statement:

USER_DEBUG [6]|DEBUG|UKGWY0000000002
USER_DEBUG [7]|DEBUG|1
USER_DEBUG [9]|DEBUG|Matched

Whereby running the test class returns below DEBUG results:
USER_DEBUG [19]|DEBUG|UKGWY0000000002
USER_DEBUG [58]|DEBUG|No Match Found
String EmailSubject = 'UKGWY0000000002 Testing 1234';
String regexMatch = '^(UKGWY\\d+\\b?)';
Pattern MyPattern = Pattern.compile(regexMatch);
Matcher MyMatcher = MyPattern.matcher(EmailSubject);
if(myMatcher.find())
system.debug(myMatcher.group());
system.debug([SELECT COUNT() FROM project__c WHERE Name =:myMatcher.group()]);
IF ([SELECT COUNT() FROM project__c WHERE name =:myMatcher.group()] == 1)
system.debug('Matched');



My custom email handler class is as below
global class CI_EmailToSalesForce implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                                                         Messaging.Inboundenvelope envelope) {
  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

//Set the Regex Matching Pattern to look for Project number in the email subject heading
String EmailSubject = email.subject;
String regexMatch = '^(UKGWY\\d+\\b?)';
//Declare a new instance of the Project object
project__c p;

try {

    // Check to see if the email subject contains any project ID
    Pattern MyPattern = Pattern.compile(regexMatch);
    Matcher MyMatcher = MyPattern.matcher(EmailSubject);
    if(myMatcher.find()){
        System.debug(myMatcher.group());
    }    
    //Condition if there is exactly one project ID match from email subject
    if ([SELECT COUNT() FROM project__c WHERE Name =:myMatcher.group()] == 1) {
    system.debug('Matched');
    p = [SELECT ID FROM project__c WHERE Name =:myMatcher.group()];
    Note note = new Note();
    note.Title = email.fromName + '(' +DateTime.now() + ')';
    note.Body = email.plainTextBody;
    note.ParentId = p.Id;
    insert note;

      // Save attachments, if any 
      if (email.binaryAttachments!=null && email.binaryAttachments.size() > 0) { 
        for (Messaging.Inboundemail.BinaryAttachment bAttachment :email.binaryAttachments) { 
        Attachment attachment = new Attachment(); 
        attachment.ContentType = bAttachment.mimeTypeSubType; 
        attachment.Name = bAttachment.fileName; 
        attachment.Body = bAttachment.body; 
        attachment.ParentId = p.Id; 
        insert attachment; 
        } 
      } 
 
      else if (email.textAttachments!=null && email.textAttachments.size() > 0) { 
        for (Messaging.Inboundemail.TextAttachment tAttachment :email.textAttachments) { 
        Attachment attachment = new Attachment(); 
        attachment.Name = tAttachment.fileName; 
        attachment.Body = Blob.valueOf(tAttachment.body); 
        attachment.ParentId = p.Id; 
        insert attachment; 
        } 
      }        

    }
    //Condition if there are more than one project ID match from email subject
    else if ([SELECT COUNT() FROM Project__c WHERE Name =:myMatcher.group()] > 1) {
    system.debug('More than 1 project ID found');
    } else {
      system.debug('No Match Found');
      }
    
    result.success = true;
    } catch (Exception e) {
      result.success = false;
      result.message = 'Oops, I failed.';
    }
   
    return result;
  }
}

Test Class
 
@IsTest
public class CI_EmailToSalesForce_Test {
    static testMethod void testCI_EmailToSalesForce() {
        // Create a new email, envelope and attachment object
        Messaging.InboundEmail email  = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        Messaging.InboundEmail.BinaryAttachment att = new Messaging.InboundEmail.BinaryAttachment();

        // Setup the data for the email
        email.subject = 'UKGWY0000000002 This is a test';
        email.plainTextBody = 'This should become a note';
        env.fromAddress ='something@something.com';
        String contactEmail = 'something@something.com';
        att.body = blob.valueOf('test attachment');
        att.fileName = 'testfile.txt';
        att.mimeTypeSubType = 'text/plain';
        
        email.binaryAttachments = new Messaging.InboundEmail.binaryAttachment[] {att};
        
        // Call the TSG_Email class and test this with the above data
        CI_EmailToSalesForce CI_EmailObjTst = new CI_EmailToSalesForce();

        Test.startTest();
        CI_EmailObjTst.handleInboundEmail(email, env);
        Test.stopTest();

    }
}

​Can anyone tell me what I have done wrong?

Kind regards,
Chris
hai.huanghai.huang
You need to insert a test data to project__c in your test class.
@IsTest
public class CI_EmailToSalesForce_Test {
    public static testMethod void testCI_EmailToSalesForce() {
        // https://developer.salesforce.com/forums/?id=906F0000000D6P7IAK
        // Create a new email, envelope and attachment object
        Messaging.InboundEmail email  = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        Messaging.InboundEmail.BinaryAttachment att = new Messaging.InboundEmail.BinaryAttachment();

        // Setup the data for the email
        email.subject = 'UKGWY0000000002 This is a test';
        email.plainTextBody = 'This should become a note';
        env.fromAddress ='something@something.com';
        String contactEmail = 'something@something.com';
        att.body = blob.valueOf('test attachment');
        att.fileName = 'testfile.txt';
        att.mimeTypeSubType = 'text/plain';
        
        email.binaryAttachments = new Messaging.InboundEmail.binaryAttachment[] {att};
        
        // Call the TSG_Email class and test this with the above data
        CI_EmailToSalesForce CI_EmailObjTst = new CI_EmailToSalesForce();
// create project test data
project__c pj = new project__c();
pj.name = 'UKGWY0000000002';
        Test.startTest();
 insert pj;
        Messaging.InboundEmailResult result = CI_EmailObjTst.handleInboundEmail(email, env);
        Test.stopTest();
    }
}
Or use "set all data true "( not recommend)



Answered by iPhone.
hai.huanghai.huang
Sorry for missing typing, the second way should be 
@isTest(SeeAllData=true)
public class CI_EmailToSalesForce_Test {
....
}
It may change your record in project during test, so it is not recommend.