Troubleshooting Email to Case

Author posted by Jitendra on Posted on under category Categories Salesforce and tagged as Tags , with 15 Comments on Troubleshooting Email to Case

In Previous article, I have explained that how to configure Email to Case Agent for creating of cases in Salesforce. This article depicts how to troubleshoot few common problems of Email to case or On Demand Email to Case.

Q 1 : Why reply to email is also becoming new Case instead of Comment on existing Case?
Ans : We need to include {!Case.Thread_Id} field in Subject line or body then only it will be added in “Open Activity” Section.

Also, Go to “Setup | App Setup | Customize | Cases | Email-to-Case “. There is a section on the Email-to-Case Settings page that says: “When sending email from a case, insert Thread ID in the following sections:” make sure that there is a check for Subject and Body. This will place a ThreadID on the email being sent from the Case. The ThreadID is a reference number that gets checked when coming back into Salesforce and will route itself to the right Case instead of creating a new one.

Q 2 : I want reply added as Comment but not as Activity in Email to case. How to do this?
Ans :
A workflow rule + an apex trigger would work.

  • Make a custom field on Case called “last email.” Don’t show it on any page layout.
  • Make a workflow rule on Email Message which copies the text of the email to that field.
  • Make an Apex trigger on Case which takes that field and makes a new comment out of it.
trigger commentMove on Case (after update) {
  Case myCase =[0];
  if (myCase.Last_email__c!= null) {
    String caseId= myCase.ID;
    CaseComment cc = new CaseComment(CommentBody=myCase.Last_email__c,parentID=caseId);
    insert cc;

Q 3 : I want to break Auto Reply (Out of Office Message, On Leave Message) to Auto Response for Email to case. How to achieve this?
Ans : There is exactly no full proof solution to this problem but we can try to check if reply is coming on Same day (We can also check if reply is coming in 5 minutes or 10 minutes). Below Trigger will help to break this loop if there are atleast 4 emails and last email was less than 5 minutes:

trigger LoopKiller on Case (before insert) {
  * Email Loop Killer
  * Will not process new email if there are atleast 4 emails from
  * the same email with the same subject and the previous email was less than 5 minutes ago
  case[] c =;

  case[] check = [select ID, CreatedDate, subject from Case where SuppliedEmail = :c[0].SuppliedEmail and subject = :c[0].subject and isclosed = false order by CreatedDate desc];

  if(c[0].Subject != null) {
    //We have a subject, proceed.
    if(c[0].subject.contains('[ ref:')){
      //No Errors.  Email should be attached to the case.
      if(check.size() > 3){
        if((check[0].createddate.addMinutes(5) > && check[0].subject.contains(c[0].subject)){
          c[0].addError('Automatic email loop has been terminated');
          //Loop Was Killed.
          //New Case should be created now!

Youtube Video Tutorial of Email to Case Agent:

Related posts

15 thoughts on “Troubleshooting Email to Case”

  1. Hi Jitendra,

    I have a concern on Q2. It triggers even if you just edit and save the record. How can I prevent that to trigger when I am just updating the record?


  2. Hi Jitendra ,
    Great Blog…..
    Can u help me out with this requirement :
    My organisation use the EMAIL TO CASE PREMIUM APP .
    The requirement is :
    1) Create a case with Subject line (User ) —-First Case
    2) Create another case with Same Subject line [either by (Same user or different user )] .—-Second Case
    3)Now System should automatically identify it as a ” Duplicate case and close the case ” (i.e second case) .
    4)Now the Case Comments of the Closed case (i.e second case) should be added to the existing case ( i.e first case) which is open.
    Which is not achievable thru E2CP app or Case Merge Premium app.
    For this we have written a code which works 90% of our requirement.
    When i create the case manually ,we achieve the o/p as per the requirement.
    The problem is :when the cases are created VIA EMAIL:
    “Case comments of the duplicate cases are not getting added to the original case which is open”.
    Where iam missing the loop.
    Here is the code :
    trigger CaseTrigger on Case (after insert) {
    Map<String, Map<Id, Map<Case, Map>>> subjectCaseCommentsMap = new Map<String, Map<Id, Map<Case, Map>>>();
    Map subjectOpenCaseId = new Map();
    Map casesToUpdate = new Map();
    List commentsToInsert = new List();
    // Gather the subjects
    for (Case c : trigger.New) {
    if (!subjectCaseCommentsMap.containsKey(c.Subject)) {
    subjectCaseCommentsMap.put(c.Subject, new Map<Id, Map<Case, Map>>());
    // Gather all Cases with those subjects & their related CaseComments
    for (Case c : [ SELECT
    Subject IN :subjectCaseCommentsMap.keySet()
    IsClosed = FALSE
    CreatedDate ASC ]) {
    // Add this Case to the map
    if (!subjectCaseCommentsMap.get(c.Subject).keySet().contains(c.Id)) {
    subjectCaseCommentsMap.get(c.Subject).put(c.Id, new Map<Case, Map>());
    subjectCaseCommentsMap.get(c.Subject).get(c.Id).put(c, new Map());
    // Take note of the first Case for each subject
    if (subjectOpenCaseId.get(c.Subject) == null) {
    subjectOpenCaseId.put(c.Subject, c.Id);
    system.debug(‘Line 52: Found a Case ‘ + c.Subject + ‘. Related comments: ‘ + c.CaseComments);
    // Add related CaseComments to the map
    if (!c.CaseComments.isEmpty()) {
    for (CaseComment com : c.CaseComments) {
    subjectCaseCommentsMap.get(c.Subject).get(c.Id).get(c).put(com.Id, com);
    // Now see if any of those Cases need to be closed
    for (String sub : subjectCaseCommentsMap.keySet()) {
    // Only proceed if there are duplicates of this subject
    if (subjectCaseCommentsMap.get(sub).size() > 1) {
    for (Id cId : subjectCaseCommentsMap.get(sub).keySet()) {
    for (Case c : subjectCaseCommentsMap.get(sub).get(cId).keySet()) {
    // Is this Case the first Case for this subject?
    if (subjectOpenCaseId.get(sub) == c.Id) {
    // Do nothing, this is the first Case for this subject
    } else {
    // Close this Case, and clone the CaseComments
    c.Status = ‘Closed’;
    casesToUpdate.put(c.Id, c);
    system.debug(‘Line 84: Closing Case ‘ + c.Subject + ‘. Related comments: ‘ + c.CaseComments);
    for (CaseComment com : c.CaseComments) {
    new CaseComment(
    CommentBody = com.CommentBody,
    ParentId = subjectOpenCaseId.get(sub)
    system.debug(‘Line 99: casesToUpdate: ‘ + casesToUpdate);
    system.debug(‘Line 100: commentsToInsert: ‘ + commentsToInsert);
    if (!casesToUpdate.values().isEmpty()) {
    update casesToUpdate.values();
    if (!commentsToInsert.isEmpty()) {
    insert commentsToInsert;

  3. Hi Jitendra,
    I am using standard salesforce email2case.
    I would like to populate the custom case fields after the creation of an email2case.
    I have somewhere in the body of the email message information such as “subject” and “email”
    I need a bulk class and test to populate my custom case fields email2_c and subject2_c
    email2_c = email
    subject2_c = Text(255)

    Example of Body Text
    “Subject: Other
    I need to see the sea.


  4. Hello Jitendra,

    Hope your are doing good !

    I read your blog about Email- To-Case functionality,thanks for writing and sharing
    knowledge about this functionality

    organization is using On Demand Email-To-Case functionality to create
    cases in salesforce but we are getting duplicate cases problem a lot,
    right now we are using a validation rule to stop duplicate cases , we
    are adding subjects , record type and supplied information email to stop
    duplicate case as short term solution.
    But we are searching a
    permanent solution for this problem, could you please help me out and
    provide your suggestion on this . i also read your trigger solution for
    automatic reply ,could you please also provide some more details about
    that as well.. as we are also getting duplicate cases due to automatic
    replies as well.

    looking forward for your suggestion ,Thanks in Advance !

    Thanks & Regards,

    1. Duplicate case is becoming because of auto reply or its really multiple emails sent ? Permanent solution would to have a trigger written on Case object. Another “point & Click” solution is to have a Text field marked as “unique” and use workflow rule to populate that field. You need to perform one time job to calculate unique field on existing cases.

      1. Thanks for your reply Jitendra, Could you please explain workflow solution a little more more specially the last line ” You need to perform one time job to calculate unique field on existing cases.” . if i make a unique text field of case subject , then would it work ? And what other conditions i need to give so that it would not stop to create genuine cases .
        i think we are getting duplicate case because of both of the conditions , due to automatic replies as well as multiple mails.we are getting duplicate cases for different-2 subjects.
        and Could you please also provide the complete code for trigger as what code we need to put at the place of comments (like at line no 16,14,21,23) ..

        if(c[0].Subject != null) {
        14 //We have a subject, proceed.
        15 if(c[0].subject.contains(‘[ ref:’)){
        16 //No Errors. Email should be attached to the case.
        17 }else{
        18 if(check.size() > 3){
        19 if((check[0].createddate.addMinutes(5) > && check[0].subject.contains(c[0].subject)){
        20 c[0].addError(‘Automatic email loop has been terminated’);
        21 //Loop Was Killed.
        22 }else{
        23 //New Case should be created now!
        24 }
        25 }
        26 }

  5. Hi
    I have a scenario for Email-to-Case functionality where are not using thread id in subject. And there is trigger on Email Message when the agent is replying back to customer we cc’ing salesforce to capture response of the agent also. But it creates new case and in the trigger handler we are creating EmailMessage and Attachment with values from newly email message and tag it to existing case. But there we are running in to concurrent issue and OBJECT_LOCK_ROW issues. Can you please help us with best approach to it

    1. Hi Vijay,
      These kind of error are not because of one functionality but mostly accumulated over the time with lots of customization in Trigger. Possible reason is Data Skew. Are you having any parent record which has many childs like more than 10k. When you create a case, are you attaching this case to any generic parent record ?

      1. Hi Jitendra,

        Thanks for acknowledging quickly. To be more specific below are the details.

        1.Agent is trying to reply back to Case . And a copy of mail sent to salesforce Id also.
        2.Then new email message object gets created with from new case and we are trying to re tag email message and respective attachment to existing case. We have taken this approach as client doesn’t want thread Id to be displayed in Subject.
        After insert of new email message from trigger we are deleting new case created which will delete all children object records.

        1. You need to check (debug) all cascading DML as well. From Case trigger, does any code try to update common parents like contact. You can delegate case deletion task to asynchronous Apex

          1. Should I send the code snippet from trigger handler . It looks little untidy as I taking over it from different team to support issues

  6. can anyone tell me how to populate account name through email to case, i know manually we can. But through email to case, a case will be generated but account name and contact name will be blanked. my requirement is fill the account name if an existing user is sending the email and if new user is sendiing the email then we have to create a account first and auto populate that account. this kind of possible through trigger . but if someone can give more insights would be really helpful to start off

  7. Hi.. I am creating an auto case from email to case. After getting the auto created case, I can see there are extra things added in the description of the case. How to prevent this extra description in the auto created cases.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.