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
Varun SuraganiVarun Suragani 

how to change case feed email from address through apex

Hi All,

Can you anyone help me with the below scenario.

Scenario :

We have an email to case functionality where we have a generic email address and those who are having the issues ( vendor - inside customers) will send an email to that email and case will automatically be created. 

Here the issue starts in 2 ways :

1)  When a customer directly sends an email to email box (email to case functionality in salesforce) case will be created automatically and it is working absolutely fine with standard functionality.

2) when a customer sends an email to an email box with some other people in CC.

Example :

To address : XXX@.....com
From : YYY@gmail.com
CC :   123@gmail.com, 000@gmail.com.


The issue here is when someone from CC is trying to reply from email box which does not have an email thread, salesforce will automatically creating new case even the subject is same and which starts with RE: (subject). 

For this we tried to write a trigger on email object where RE:, FW: emails have to come into one email so that new cases will not create.

Below is the code. 


public class EmailMessageHandler {
 
 
  public static void afterInsert(List<EmailMessage> newEmailMessagelist){
    
    Set<Id> parentIds = new Set<Id>();
    String[] prefixes = new String[] {'fw:','re:', 'automatic reply:', 'out of office autoreply:', 'out of office'};  
    for(EmailMessage objEmailMessage : newEmailMessagelist){
        String target = objEmailMessage.Subject.toLowerCase();
        for(String prefix: prefixes) { 
            Integer index = target.indexOf(prefix); 
            if(index == 0 ){
                System.debug(objEmailMessage.parentId);
                parentIds.add(objEmailMessage.parentId); 
            }   
        }
    }
    list<Case> caselist = new List<Case>([Select Id,SuppliedEmail,Attachment_Available__c,All_Tax_Refund__c,Previous_Case_Reject_reason__c,Status,                                      Case_Reject_Reason__c,Subject,RecordTypeId,Internal_Contact1__r.Email,contactId,Account.Owner.Email,AccountId,
                                        Internal_Contact2__r.Email,Internal_Contact3__r.Email,Internal_Contact4__r.Email,Type,Case_Escalation_Comments__c,
                                        CaseNumber,Description,Internal_Contact5__r.Email from Case Where ID IN : parentIds]); 
            
            
        Set<String> setSubjects = new Set<String>();
        Map<id,Case> mapCase2 = new Map<Id,Case>();
        for(case objCase : caselist ){
       
            if(extractMainSubject(objCase.subject) != null){
                setSubjects.add(extractMainSubject(objCase.subject).trim());
            }
            system.debug(setSubjects);
            
        }
        case[]  matchingCases = [Select Id, CaseNumber, Subject, Description from Case where Subject IN :setSubjects];
        if(!matchingCases.isEmpty() || test.isRunningTest()){
            Map<String,Id> mapCaseSubjectId = new Map<String,Id>();
            for(Case objCase: matchingCases ){
                mapCaseSubjectId.put(objCase.subject,objCase.Id);
            }
            List<EmailMessage> newEmailMessage = new List<EmailMessage>();
            List<Case> listCase = new List<Case>();
            set<Id> setCaseToDelete = new Set<Id>();
            
            
            for(EmailMessage objEmailMessage : newEmailMessagelist){
                    System.debug(objEmailMessage.parentId);
                    
                    if(extractMainSubject(objEmailMessage.subject) != null && mapCaseSubjectId.containsKey(extractMainSubject(objEmailMessage.subject).trim())){
                    setCaseToDelete.add(objEmailMessage.parentId);                  
                    newEmailMessage.add(new EmailMessage(FromAddress = objEmailMessage.FromAddress,
                                                             CcAddress= objEmailMessage.CcAddress,
                                                             FromName = objEmailMessage.FromName ,
                                                             ToAddress = objEmailMessage.ToAddress,
                                                             Subject = extractMainSubject(objEmailMessage.subject).trim() ,
                                                             TextBody = objEmailMessage .TextBody,
                                                             HtmlBody = objEmailMessage .HtmlBody ,
                                                             ParentId = mapCaseSubjectId.get(extractMainSubject(objEmailMessage.subject).trim())
                                                             ));
                   }
            }
                  
                  
            if(!newEmailMessage.isEmpty())
                insert newEmailMessage;
                
            if(!setCaseToDelete.isEmpty())
               deleteCases(setCaseToDelete);
        }
             
           
      }          
        
        
            @future(callout=false)
            static void deleteCases(Set<Id> CaseIds){
                delete [select Id from Case where id IN : CaseIds];  
            }
         
            private Static String extractMainSubject(String emailSubject){
                String tempSub = emailSubject;
                if(emailSubject == null || emailSubject.length() < 3){
                    emailSubject = null;
                }
                String[] prefixes = new String[] {'fw:','re:', 'automatic reply:', 'out of office autoreply:', 'out of office'};  
                String target = emailSubject.toLowerCase();
                boolean isDUP = false;
                
                for(String prefix: prefixes) {
                    Integer index = target.indexOf(prefix); 
                
                    if(index == 0 ){
                    isDUP = true;
                    emailSubject = tempSub.substring(prefix.length(),tempSub.length());
                    } else if(!isDUP  )  {emailSubject = null;}
                }
                return emailSubject; 
            }
            
          
 }



The issue I'm facing here is, I'm getting different from address and to address in the case feed email and where if I try to open that email or view the email from address and to address are same.


Please, can anyone please try to explain where I'm doing wrong and thanks for the patience to read this issue.
Varun SuraganiVarun Suragani
Any one facing the same issue??