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
JaiJai 

please help me on the following scenario

Need to implent apex code when new email received to the case then case status should picklist update to 'New Email Received'

I written the following code but it is not working as expectd please corret me 

public class UpdateCasestatusHandlere {
    
    Public static void updateCasestatus(List<EmailMessage> newmailoncase)
    {
        Set<Id> caseIdSet = new Set<Id>();
    List<Case> caseUpdate = new List<Case>();
    List<Case> updatecase = new List<Case>();
    for(EmailMessage em : newmailoncase)
    {
        if(em.Incoming && em.FromAddress == 'jtalapala@aligntech.com')
        {
        caseIdset.add(em.ParentId);
        }
    }
    
    caseUpdate = [select id, Status,(select id, ParentId from EmailMessages) from Case where id In : caseIdset];
    for(Case cse : caseUpdate)
    {
       cse.Status = 'New Email Received' ;
        updatecase.add(cse);
        
    }
        if(!updatecase.isEmpty() && updatecase.size()>0)
        {
update updatecase;
        }
    }

}

Thanks!!!
PriyaPriya (Salesforce Developers) 

Hey Jai,

What is the error coming in this? 

Also you can do this with workflow rule.  check this document :- 
https://help.salesforce.com/s/articleView?id=000330183&type=1

For more, refer this :- 
https://www.salesforceben.com/update-case-status-sending-receiving-email/


Kindly mark it as the best answer if it helps.

Thanks,

Priya Ranjan