+ Start a Discussion
SFDC Apex DevSFDC Apex Dev 

Need to write trigger on EmailMessage

Here is the Scenario:
We're having Email-to-Case functionality. Whenever a new Email received on case the case field Status Alert should get updated with value "Received" and when replied to that email same field should get blank.

Can anyone please help me out with this trigger?
 
trigger emailMessageTrigger on EmailMessage (before insert, before update) {
    Set<Id> caseIdSet = new Set<Id>();
    list<Case> casList = new list<Case>();
    
    for(EmailMessage email: Trigger.new){
        caseIdSet.add(email.ParentId);
    }
    
    if(caseIdSet != null && caseIdSet.size() > 0){
        casList = [Select Id, Status, Status_Alert__c from Case where Id IN: caseIdSet AND Status != 'New' AND Status_Alert__c	!= 'New Email Received'];
    }
    
    for(EmailMessage newEmail: Trigger.new){
        if(casList.size() > 0){
            for(Case cas: casList){
                cas.Status_Alert__c	 = 'New Email Received';
                update cas;
            }
        }
    }
}

 
ShirishaShirisha (Salesforce Developers) 
Hi Chirag,

Greetings!

Can you please check the below article which will help in updating based on the email received functionality without creating any custom code:

https://help.salesforce.com/articleView?id=000330183&type=1&mode=1

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
SFDC Apex DevSFDC Apex Dev
Hi Shirisha,

We're removing  workflow rule and implementing the same with help of trigger.

Thanks!
Chirag