+ Start a Discussion
rajesh kamath 16rajesh kamath 16 

InboundEmailHandler Issue

Hello Geeks,

I am stuck and need a help. I have a requirement as follows, Consider a user sends an email with the body and an email subject line as "Subject: Hello 00001043" where 00001043 can be any case number. Now as per my requirement I need two things to be handled.
1. Firstly I need to parse the subject line of the email which user has sent and get the case number from the subject line and match the case number from the subject line with the case number of all the case records in the database. 
    a) If there are any matching case records with the case number from the subject line, then I simply need to attach the email in the email related list of the matched case record.

    b) If no case records are presents with the case number as per the subject line, then only I need to create a new case record with that email sent to be attached to this newly created case record.
    
I have used Email-to-case functionality, where whenever user sends any mail, a new case record gets created automatically irrespecttive of the case number mentioned in the subject line. Say the case with the case number in the subject line if already present in database still it creates new case record and attaches the email to new record. But I want the email to get attached to the old matched record instead of new case to be created.

To handle it I am using InboundEmailHandler code which I am triggering out using Email Service: Execute on Inbound by selecting that apex class but not getting a way out to proceed further. Can anyone help me out in the logic. I am attaching my entire code. Any help would be highly appreciated.

Thanks.

Code:

Global class EmailToCase implements Messaging.InboundEmailHandler
{
    Global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope env ) 
    {
        //Create an inboundEmailResult object for returning the result of the email service.
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
                 
        //Convert the subject line to ignore the case so the program can match on lower case or upper case.
        String mySubject = email.subject.equalsIgnoreCase();
        
        //String to hold the numbers from the subjectLine
        String caseIdInSubjectLine = '';

        //Check if the numbers are present in the subjectLine
        for(String str : mySubject.split('(?!^)'))
        {
            //Fetch only the numbers from the subjectLine for comparision 
            if(str.isNumeric())
            {
                //Hold the numbers from the subjectLine into a String variable
                caseIdInSubjectLine += str;
            }
        }
        
        //Check if the subject line has a case number
        if(caseIdInSubjectLine != null || caseIdInSubjectLine!= '')
        {
            //List to insert case records to database
            List<Case> lstCaseRecordsToInsert = new List<Case>();
            
            //Fetch all the cases whose case number from the subject line matches with the case records from the database
            List<Case> matchingCases = [Select Id, CaseNumber, Subject, Description From Case Where CaseNumber = :caseIdInSubjectLine];
            
            //Check if there are matched case records
            if(!matchingCases.isEmpty())
            {
                //Simply handled if more than 1 case records with case number are being matched
                if(matchingCases.size() == 1)
                {
                    //Iterate over the matched case records
                    for(Case objMatchedCase : matchingCases)
                    {
                        //Here i want my email to be attached to the matched case
                    }        
                }
                else
                {
                    system.debug(Logginglevel.ERROR, 'EmailToCase.  Create a new case because we found '+matchingCases.size() + ' cases with the subject: "' + mainSubject + '"');
                }
            }
            else
            {
                //Create a new case record 
                Case objCaseToInsert = new Case();
                objCaseToInsert.SuppliedEmail = email.fromAddress;
                objCaseToInsert.SuppliedName = email.fromName;
                objCaseToInsert.Status = 'New';
                objCaseToInsert.Priority = 'Low';                
                objCaseToInsert.Origin = 'Email';
                
                //Subject from the email
                String extractedSubject = email.subject;        
                objCaseToInsert.Subject = extractedSubject;
                objCaseToInsert.Description = email.plainTextBody;
                
                //Add the case records to a list
                lstCaseRecordsToInsert.add(objCaseToInsert);
            }
            
            //If the list contains some values
            if(!lstCaseRecordsToInsert.isEmpty())
            {
                insert lstCaseRecordsToInsert;
            }
        }
        else
        {
            //No case number in the subject line, so do nothing
        }    
    }        
}
Best Answer chosen by rajesh kamath 16
Chandra Sekhar CH N VChandra Sekhar CH N V
Rajesh,

As per my understanding, you will also have Thread ID (something like -ref:897fbsnfbsf:ref) in the email. 

When a user sends email for the first time, a case will be created in salesforce. And in case there are any further communications in the same email, the corresponding emails will be attached to the case automatically based on the unique thread ID in the subject line.

You will find duplicate cases created only when such emails for the same case have no thread ID present.

Please check below post if it is usefule to you - 
http://sforcehacks.blogspot.in/2012/01/email-to-case-can-create-too-many-cases.html
 

All Answers

Chandra Sekhar CH N VChandra Sekhar CH N V
Rajesh,

As per my understanding, you will also have Thread ID (something like -ref:897fbsnfbsf:ref) in the email. 

When a user sends email for the first time, a case will be created in salesforce. And in case there are any further communications in the same email, the corresponding emails will be attached to the case automatically based on the unique thread ID in the subject line.

You will find duplicate cases created only when such emails for the same case have no thread ID present.

Please check below post if it is usefule to you - 
http://sforcehacks.blogspot.in/2012/01/email-to-case-can-create-too-many-cases.html
 
This was selected as the best answer
rajesh kamath 16rajesh kamath 16
Thanks @Chandra :)