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
Hermann OuréHermann Ouré 

Trigger to stop clients from Sending emails on Case Closed

Hello, 
I am trying to create a trigger to stop clients from sending emails on Case closed. But it doesn't work.
Could someone help?
Thanks,

Apex Class:

public class EmailManager {
    
    public static void sendEmailToCaseDeactivated(){
        
        //Use classic email template
        EmailTemplate templateId = [SELECT Id FROM EmailTemplate WHERE DeveloperName =:'Smart_Community_Email_to_Case_Deactivated'];
        List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        mail.setTargetObjectId(UserInfo.getUserId());
        mail.setTemplateId(templateId.Id);
        mail.setSaveAsActivity(false);
        allmsg.add(mail);
        
        Messaging.sendEmail(allmsg, false);
        
    }
        
}
Apex Trigger:
trigger IncomingEmailClosedCase on EmailMessage (before insert) {
   
    Set<Id> caseIds = new Set<Id>();
    
    for(EmailMessage em: Trigger.New) {
        if (em.Incoming == true) caseIds.add(em.Id);   
    }
    
    List<Case> lstCase = new List<Case>([SELECT Id, Status FROM Case WHERE Status = 'Closed' AND Id In: caseIds]);
    
    if(lstCase.size() > 0) {
        EmailManager.sendEmailToCaseDeactivated();
    }
   
}


 

ANUTEJANUTEJ (Salesforce Developers) 
Hi Hermann,

The above feature you have mentioned is currently is present as an idea that you can check in the below link: https://trailblazer.salesforce.com/ideaView?id=08730000000ZEkWAAW

You can upvote so that it may be considered in the future if the upvotes reach a certain threshold.

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.  

Thanks.