+ Start a Discussion
Sindhu NagabhushanSindhu Nagabhushan 

Before insert trigger on Email Message object

Hi,
I need help in writing before insert trigger on Email Message
My Requirement is - 
    If sender address is already present in web email of any case, the incoming email should attach to that case.
    
    Please help me how to write this trigger.
    I have created thread id formula field to update the thread id of the case.

Thanks in Advance
Anupam RastogiAnupam Rastogi
Hi Sindhu,

The code should be similar to what I have written below. Replace the exact object name and fields as per the configurations you have in your Organization.
 
trigger AssociateEmail on EmailMessage (before insert) {

    for(EmailMessage eMsg : Trigger.new) {
        
        String eThreadId = EmailMessage.Thread_Id__c;
        String eWebAdd = EmailMessage.Web_Address__c;
        
        //---Ideally this query should return only one record because we have queried using Thread Id
        List<Case> c = [select Id from Case where ThreadId = :eThreadId
                       and SenderAddress = :eWebAdd];
        
        if(c.size() > 0) {
            
            EmailMessage.WhatId = c.Id;
        }
    }

}

For the above code replace the following per your application - 

EmailMessage - Replace it with the object name
EmailMessage.Thread_Id__c - Replace it with the field present on the above object that is storing the Thread Id
EmailMessage.Web_Address__c - Replace it with the field present on the above object that is storing the Web Address of the sender
ThreadId - Replace it with the formula field present on Case
SenderAddress - Replace it with the field present on Case that stores the sender's email address

Thanks
Anupam