Thursday, January 5, 2012

Email-To-Case custom email handler - Part 2

Well the email handler is working well with only one problem. The idea to locate the Case based on subject line matching is good. But there are times when it is "too good" and two unrelated emails can be placed into the same case. Before discussing the fixes let's look at the code.
Refer to the posting Email-to-Case can create too many cases.


IN the method processInboundEmail look for the code that locates cases based on subject line. Here is the before:

...
else {
  // try to match subject
  String mainSubject = extractMainSubject(email.subject);
  Case[] matchingCases = [Select Id, CaseNumber, Subject, Description from Case where Subject = :mainSubject
   and CreatedDate = LAST_N_DAYS:5];
  if(matchingCases.size() == 1) {
   this.theCase = matchingCases[0];
  } else 
  {
   system.debug(Logginglevel.ERROR,'CaseEmailInBoundUtilities.  Create a new case because we found '+matchingCases.size() + ' cases with the subject: "' + mainSubject + '"');
  }
 }
....

This works well for normal issues that have some substantial subject line. But what about those simple topics like "Ordering", or "Inquiry" or even an empty subject line.

Quick fix
...
// try to match subject
String mainSubject = extractMainSubject(email.subject);
// Only try to match non-trivial subject lines. Otherwise too many different issues can me merged into one case.
if(mainSubject!=null && mainSubject.length() > 15) {
 // Only match subjects on cases Created in the last 5 days. 
 Case[] matchingCases = [Select Id, CaseNumber, Subject, Description 
  from Case where Subject = :mainSubject
  and CreatedDate = LAST_N_DAYS:5];
...

Better Fix
Someday or someone else might create a solution that refines the match to cases that have similar recipients on the email thread.

No comments:

Post a Comment