+ Start a Discussion
sumit dsumit d 

trigger on EmailMessages on Case

Hi All,
      my requirement is  to Create a trigger that uses the From Address of the Email Message object on a new Case to update the Case Owner. The Case Owner will be the user that sent the email and will be identified by their email address as it corresponds to active users on the user table 

FromAddress = User.Email the assign CaseOwner = User.Id 
my triggerHelper class is as follow:-
public class EmailMessageTriggerHelper {
    
    public static List<EmailMessage> newEmailMessages = new List<EmailMessage>();
    public static List<EmailMessage> oldEmailMessages = new List<EmailMessage>();
    public static Map<Id, EmailMessage> newMapEmailMessages = new Map<Id, EmailMessage>();
    public static Map<Id, EmailMessage> oldMapEmailMessages = new Map<Id, EmailMessage>(); 
          
    public static void UpdateOwner(){
        set<Id> caseIds = new set<Id>();
        map<Id,string> case2OwnerValueMap = new map<Id,string>();
        for(EmailMessage message : newEmailMessages){
            if(message.Incoming == false){
                string OwnerValue;
                message.FromAddress = String.Valueof(User.Email);

            caseIds.add(message.ParentId);
            case2OwnerValueMap.put(message.ParentId, OwnerValue);
        }
    }
    list<Case> casesToUpdate = [Select Id, OwnerId   From Case Where Id in: caseIds];
    for(Case c : casesToUpdate){
        c.OwnerId = case2OwnerValueMap.get(c.Id);
    }

    update casesToUpdate;
        
     }    
}
Am i missing something?
guide me?
Any suggestions?
Best Answer chosen by sumit d
Vishal_GuptaVishal_Gupta
Hi Sumit,

You have missed to fill the valure in Owner in your map, please fill it with the user Id related to the from email address. 

           string OwnerValue;
           message.FromAddress = String.Valueof(User.Email);

            caseIds.add(message.ParentId);
            OwnerValue = [Select id from user where email = :emailMsg.FromAddress Limit 1];
            case2OwnerValueMap.put(message.ParentId, OwnerValue);

Please let me know if its resolve your issue.