I am trying to add a trigger to route emails. The criteria are, if a case is opened from email-to-case and remains open while there are email messages being sent between representatives and customers the emails will attach to the open case. If the case is closed, any emails pertaining to that case will open a new case and while that case is open any correspondance will remain on that case.

My logic is working between messages being filtered between the first original open case. When that case is closed and a customer replies back it opens a new case successfully. I am running into an issue where a customer replies back to an email to the new open case that is created.

I think this is an email token issue. The email see's the closed case of the original case and creates a new case because the original is closed.

trigger EmailToCase on EmailMessage (before insert) {
List<EmailMessage> comments = new List<EmailMessage>();
for (EmailMessage message : trigger.new) {
    Id caseId = message.ParentId;
    //find the case in the system
    String query = 'SELECT ' + Utilities.GetAllSelects('Case') + ' FROM CASE WHERE Id = :caseId';
    List<Case> cases = System.Database.query(query);
    //if this is an existing case it will see if it is open/closed
    if(cases.size() > 0){
        Case emailToCase = cases.get(0);
        //if this case is closed it will open a new case
        if(emailToCase.Status == 'Closed'){
            emailToCase.Status = 'New';
            sObject closedCase = emailToCase;
            Sobject newCase = closedCase.clone(false, true);
            insert newCase;
            //setting email to open/new case
            message.ParentId = newCase.id;
            message.Subject = '';


1 Answer 1


I my view you do not need to write a trigger to attain the functionality you have mentioned above. It is already present as a standard one. When a case is open via email-to-case it gets assigned a tread id. In all your email communication templates place this Thread id either in Subject/body of the email. Any emails sent as reply will check this thread id and will attach to the original case.

Now once the case is closed and a new email reply is sent on the same case then have a workflow rule to either send a reply to customer to open a new case/or make any field update on old case which can be tracked by you to open a new case. Then this new case will have a new Thread id and any mails sent from this case will attach to the new ones.

Refer the below link for more details: http://www.salesforceben.com/thoughts-reopening-closed-case-salesforce/

Hope this helps you.

Thanks! Ruchika

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .