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
jaishrijaishri 

i have a code in trigger when case is closed,create and delete send a email to case contact when case is delete how to send a email to case contact can anyone help me to provide solution

trigger CaseEmail on Case (after insert, after update,before delete) {
    
   If((Trigger.isUpdate || Trigger.isinsert) && Trigger.isafter){
       Set<Id> conIds = new Set<Id>();
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    for (Case c: trigger.new) {
        conIds.add(c.ContactId);
   }
    Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
    
    for (Case c : trigger.new) {
        if (c.status == 'Closed') {
            Contact relatedCaseContact = conMap.get(c.ContactId);
            
            Messaging.SingleEmailMessage CaseNotificationmail = new Messaging.SingleEmailMessage();  
            CaseNotificationmail.setToAddresses(new List<String> { relatedCaseContact.Email });
            CaseNotificationmail.setReplyTo('jayati.shukla.sbg@gmail.com');
            CaseNotificationmail.setSenderDisplayName('Salesforce');            
            
            CaseNotificationmail.setSubject(' Case Status updation  ' + 'Changed to ' + c.status + ' Case Number:' + c.CaseNumber);
            CaseNotificationmail.setPlainTextBody(' Your case Status for Case Number: ' + c.CaseNumber + '  Related Case Contact:' +c.ContactId +' has been closed '); 
            mails.add(CaseNotificationmail); 
        }
        
        if(Trigger.isinsert && Trigger.isafter){
            Contact relatedCaseContact = conMap.get(c.ContactId);
                   Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
        mail.setToAddresses(new List<String> { relatedCaseContact.Email });
        mail.setSubject('New Case Create: '+ c.CaseNumber);
        String body = 'Case is created. Thank you for contacting us';
        mail.setHtmlBody(body);
        mails.add(mail);
        }
    }
 Messaging.sendEmail(mails);
   }
    if(Trigger.isDelete && Trigger.isBefore){
       Set<Id> conIds = new Set<Id>();
      List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
         Map<Id, Contact> conMp = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
    for (Case cs : Trigger.old) {
         Contact relatedCaseContact = conMp.get(cs.ContactId);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
        email.setToAddresses(new List<String> { relatedCaseContact.Email  });
        email.setSubject('Case Deleted');
        email.setPlainTextBody('This message is to alert you that the Case number' + cs.CaseNumber + ' has been deleted. Thank you for contacting us.');
        emails.add(email);
    }
    Messaging.sendEmail(emails);
}
    }
Best Answer chosen by jaishri
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Can yoy check the below article . It explains why this issue usually occurs.

https://help.salesforce.com/s/articleView?id=000353740&type=1 (https://help.salesforce.com/s/articleView?id=000353740&type=1)

Thanks,
 

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Can you confirm what is the issue with the above code. Is it not working or what excatly are you having issue with above.

Thanks,
 
jaishrijaishri
Code is working properly in above code when case is create or closed it sends a mail to contact case  it is correct when i'm trying to when case is deleted  it also send email to related  case contact but it is not working  error  .......There's a problem saving this record. You might not have permission to edit it, or it mig
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

I have made small change in the code. Added the highlited part because of which you are facing error.
 
trigger CaseEmail on Case (after insert, after update,before delete) {
    
   If((Trigger.isUpdate || Trigger.isinsert) && Trigger.isafter){
       Set<Id> conIds = new Set<Id>();
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    for (Case c: trigger.new) {
        conIds.add(c.ContactId);
   }
    Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
    
    for (Case c : trigger.new) {
        if (c.status == 'Closed') {
            Contact relatedCaseContact = conMap.get(c.ContactId);
            
            Messaging.SingleEmailMessage CaseNotificationmail = new Messaging.SingleEmailMessage();  
            CaseNotificationmail.setToAddresses(new List<String> { relatedCaseContact.Email });
            CaseNotificationmail.setReplyTo('sample@salesforce.com');
            CaseNotificationmail.setSenderDisplayName('Salesforce');            
            
            CaseNotificationmail.setSubject(' Case Status updation  ' + 'Changed to ' + c.status + ' Case Number:' + c.CaseNumber);
            CaseNotificationmail.setPlainTextBody(' Your case Status for Case Number: ' + c.CaseNumber + '  Related Case Contact:' +c.ContactId +' has been closed '); 
            mails.add(CaseNotificationmail); 
        }
        
        if(Trigger.isinsert && Trigger.isafter){
            Contact relatedCaseContact = conMap.get(c.ContactId);
                   Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
        mail.setToAddresses(new List<String> { relatedCaseContact.Email });
        mail.setSubject('New Case Create: '+ c.CaseNumber);
        String body = 'Case is created. Thank you for contacting us';
        mail.setHtmlBody(body);
        mails.add(mail);
        }
    }
 Messaging.sendEmail(mails);
   }
    if(Trigger.isDelete && Trigger.isBefore){
       Set<Id> conIds = new Set<Id>();
         for (Case c: trigger.old) {
        conIds.add(c.ContactId);
   }
      List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
         Map<Id, Contact> conMp = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
    for (Case cs : Trigger.old) {
         Contact relatedCaseContact = conMp.get(cs.ContactId);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
        email.setToAddresses(new List<String> { relatedCaseContact.Email  });
        email.setSubject('Case Deleted');
        email.setPlainTextBody('This message is to alert you that the Case number' + cs.CaseNumber + ' has been deleted. Thank you for contacting us.');
        emails.add(email);
    }
    Messaging.sendEmail(emails);
}
    }

If this solution helps, Please mark it as best answer.

Thanks,
 
jaishrijaishri

could you explain this code line by line it is more helpful for me please 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi
I have commented the instructions for almost all the required lines.
 
trigger CaseEmail on Case (after insert, after update,before delete) {
    
   If((Trigger.isUpdate || Trigger.isinsert) && Trigger.isafter){//This line will allow only if the record is created or edited
       Set<Id> conIds = new Set<Id>();
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    for (Case c: trigger.new) {
        conIds.add(c.ContactId);//adding the contact id so we can get the contact email for the case
   }
    Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);// quering the contact so we get the contact email
    
    for (Case c : trigger.new) {
        if (c.status == 'Closed') {// checking if the status is closed in case of create or edit scenerio
            Contact relatedCaseContact = conMap.get(c.ContactId);//getting the contact information related to particular case
            
            Messaging.SingleEmailMessage CaseNotificationmail = new Messaging.SingleEmailMessage();  
            CaseNotificationmail.setToAddresses(new List<String> { relatedCaseContact.Email });//adding to address
            CaseNotificationmail.setReplyTo('sample@salesforce.com');//adding reply to  address
            CaseNotificationmail.setSenderDisplayName('Salesforce');  //adding display name          
            
            CaseNotificationmail.setSubject(' Case Status updation  ' + 'Changed to ' + c.status + ' Case Number:' + c.CaseNumber);//adding subject
            CaseNotificationmail.setPlainTextBody(' Your case Status for Case Number: ' + c.CaseNumber + '  Related Case Contact:' +c.ContactId +' has been closed '); //adding body of the email
            mails.add(CaseNotificationmail); //adding the notification to the list so all the emails can be sent once
        }
        
        if(Trigger.isinsert && Trigger.isafter){// as we need a notification when a case is craeted
            Contact relatedCaseContact = conMap.get(c.ContactId);
                   Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
        mail.setToAddresses(new List<String> { relatedCaseContact.Email });
        mail.setSubject('New Case Create: '+ c.CaseNumber);
        String body = 'Case is created. Thank you for contacting us';
        mail.setHtmlBody(body);
        mails.add(mail);
        }
    }
 Messaging.sendEmail(mails);//sending the emails at once
   }
    if(Trigger.isDelete && Trigger.isBefore){// if the case is deleted we have to send an email so using this line and we used before because after deletion we cannot send email 
       Set<Id> conIds = new Set<Id>();
         for (Case c: trigger.old) {
        conIds.add(c.ContactId);
   }
      List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
         Map<Id, Contact> conMp = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
    for (Case cs : Trigger.old) {
         Contact relatedCaseContact = conMp.get(cs.ContactId);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
        email.setToAddresses(new List<String> { relatedCaseContact.Email  });
        email.setSubject('Case Deleted');
        email.setPlainTextBody('This message is to alert you that the Case number' + cs.CaseNumber + ' has been deleted. Thank you for contacting us.');
        emails.add(email);
    }
    Messaging.sendEmail(emails);
}
    }

Please mark this solution as best answer, It it helped you.

Thanks,
 
jaishrijaishri
Could you do one more help for me again in this above code Create the apex trigger handler class with methods and
Create a trigger and call the apex class methods in it  ................i don't know how to do
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Sure I can provide it. Is it possible to add as other question as this requires some efforts to change into handler.

Thanks,
 
jaishrijaishri
hi sai,
         this is code like if when a case is created ,closed and delete we are using insert ,update delete i want to put the logic in handler  and call method in trigger  i also provide a link https://bestirtech.com/blog/2020/09/salesforce-apex-trigger-handler/     here is sample of account trigger handler class and account trigger . Help me...
         trigger CaseEmail on Case (after insert, after update) {
    
    If((Trigger.isUpdate || Trigger.isinsert) && Trigger.isafter){
        Set<Id> conIds = new Set<Id>();
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for (Case c: trigger.new) {
            conIds.add(c.ContactId);
        }
        Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
        for (Case c : trigger.new) {
            if (c.status == 'Closed') {
                Contact relatedCaseContact = conMap.get(c.ContactId);
                
                Messaging.SingleEmailMessage CaseNotificationmail = new Messaging.SingleEmailMessage();  
                CaseNotificationmail.setToAddresses(new List<String> { relatedCaseContact.Email });
                CaseNotificationmail.setReplyTo('jayati.shukla.sbg@gmail.com');
                CaseNotificationmail.setSenderDisplayName('Salesforce');            
                
                CaseNotificationmail.setSubject(' Case Status updation  ' + 'Changed to ' + c.status + ' Case Number:' + c.CaseNumber);
                CaseNotificationmail.setPlainTextBody(' Your case Status for Case Number: ' + c.CaseNumber + '  Related Case Contact:' +c.ContactId +' has been closed '); 
                mails.add(CaseNotificationmail); 
            }
            
            if(Trigger.isinsert && Trigger.isafter){
                Contact relatedCaseContact = conMap.get(c.ContactId);
                Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
                mail.setToAddresses(new List<String> { relatedCaseContact.Email });
                mail.setSubject('New Case Create: '+ c.CaseNumber);
                mail.setPlainTextBody('Case is created. Thank you for contacting us');
                mails.add(mail);
            }
        }
        Messaging.sendEmail(mails);
    }
    if(Trigger.isDelete && Trigger.isBefore){
        Set<Id> conIds = new Set<Id>();
        for (Case c: trigger.old) {
            conIds.add(c.ContactId);
        }
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        Map<Id, Contact> conMp = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
        for (Case cs : Trigger.old) {
            Contact relatedCaseContact = conMp.get(cs.ContactId);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            
            email.setToAddresses(new List<String> { relatedCaseContact.Email  });
            email.setSubject('Case Deleted');
            email.setPlainTextBody('This message is to alert you that the Case number' + cs.CaseNumber + ' has been deleted. Thank you for contacting us.');
            emails.add(email);
        }
        Messaging.sendEmail(emails);
    }
}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi

Please try the below trigger and handler.

Trigger:
trigger CaseEmail on Case (after insert, after update,before delete) {
    
   If((Trigger.isUpdate || Trigger.isinsert) && Trigger.isafter){//This line will allow only if the record is created or edited
	CaseEmailHandler.sendemailforInsrtupdate(Trigger.new);
   }
    if(Trigger.isDelete && Trigger.isBefore){// if the case is deleted we have to send an email so using this line and we used before because after deletion we cannot send email 
	CaseEmailHandler.sendemailfordelete(Trigger.old);
}
    }

Handler:
 
public class CaseEmailHandler {

    public static void sendemailforInsrtupdate(List<Case> caselist){
            Set<Id> conIds = new Set<Id>();
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    for (Case c: caselist) {
        conIds.add(c.ContactId);//adding the contact id so we can get the contact email for the case
   }
    Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);// quering the contact so we get the contact email
    
    for (Case c : caselist) {
        if (c.status == 'Closed') {// checking if the status is closed in case of create or edit scenerio
            Contact relatedCaseContact = conMap.get(c.ContactId);//getting the contact information related to particular case
            
            Messaging.SingleEmailMessage CaseNotificationmail = new Messaging.SingleEmailMessage();  
            CaseNotificationmail.setToAddresses(new List<String> { relatedCaseContact.Email });//adding to address
            CaseNotificationmail.setReplyTo('sample@salesforce.com');//adding reply to  address
            CaseNotificationmail.setSenderDisplayName('Salesforce');  //adding display name          
            
            CaseNotificationmail.setSubject(' Case Status updation  ' + 'Changed to ' + c.status + ' Case Number:' + c.CaseNumber);//adding subject
            CaseNotificationmail.setPlainTextBody(' Your case Status for Case Number: ' + c.CaseNumber + '  Related Case Contact:' +c.ContactId +' has been closed '); //adding body of the email
            mails.add(CaseNotificationmail); //adding the notification to the list so all the emails can be sent once
        }
        
        if(Trigger.isinsert && Trigger.isafter){// as we need a notification when a case is craeted
            Contact relatedCaseContact = conMap.get(c.ContactId);
                   Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
        mail.setToAddresses(new List<String> { relatedCaseContact.Email });
        mail.setSubject('New Case Create: '+ c.CaseNumber);
        String body = 'Case is created. Thank you for contacting us';
        mail.setHtmlBody(body);
        mails.add(mail);
        }
    }
 Messaging.sendEmail(mails);//sending the emails at once   
    }
    public static void sendemailfordelete(List<Case> caselist){
               Set<Id> conIds = new Set<Id>();
         for (Case c: caselist) {
        conIds.add(c.ContactId);
   }
      List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
         Map<Id, Contact> conMp = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
    for (Case cs : caselist) {
         Contact relatedCaseContact = conMp.get(cs.ContactId);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
        email.setToAddresses(new List<String> { relatedCaseContact.Email  });
        email.setSubject('Case Deleted');
        email.setPlainTextBody('This message is to alert you that the Case number' + cs.CaseNumber + ' has been deleted. Thank you for contacting us.');
        emails.add(email);
    }
    Messaging.sendEmail(emails);
    }
    
}

Thanks,
​​​​​​​​​​​​​​
jaishrijaishri
Thank you sai 
           Can we remove this line from handler class  if(Trigger.isinsert && Trigger.isafter)
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

No you cannot remove that line because we are using the same method for update and insert. For the system to know which alert should it send we used in the handler.

Thanks,
 
jaishrijaishri
I'm trying to do only case is created or deleted it is showing error CaseEmail: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: SINGLE_EMAIL_LIMIT_EXCEEDED, Email limit exceeded: [] Class.CaseHelper.AfterInsert: line 19, column 1 Trigger.CaseEmail: line 4, column 1
Trigger
trigger CaseEmail on Case (after insert, after update,before delete) {
    
   If((Trigger.isUpdate || Trigger.isinsert) && Trigger.isafter){
    CaseHelper.AfterInsert(Trigger.new);
   }
    if(Trigger.isDelete && Trigger.isBefore){
       
    CaseHelper.BeforeDelete(Trigger.old);
}
    }
 Helper class

public class CaseHelper {
     public static void AfterInsert(List<Case> caselist){
        Set<Id> conIds = new Set<Id>();
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for (Case c: caselist) {
            conIds.add(c.ContactId);
        }
        Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
        for (Case c : caselist) {
            Contact CaseContact = conMap.get(c.ContactId);
            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
            mail.setToAddresses(new List<String> { CaseContact.Email });
            mail.setSubject('New Case Create '+  c.CaseNumber);
            mail.setPlainTextBody('Case is created Thank you for contacting us');
            mails.add(mail);
            
        }
        Messaging.sendEmail(mails); 
    }
    public static void BeforeDelete(List<Case> caselist){
        Set<Id> conIds = new Set<Id>();
        for (Case c: caselist) {
            conIds.add(c.ContactId);
        }
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        Map<Id, Contact> conMp = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
        for (Case cs : caselist) {
            Contact CaseContact = conMp.get(cs.ContactId);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            
            email.setToAddresses(new List<String> { CaseContact.Email  });
            email.setSubject('Case Deleted');
            email.setPlainTextBody('This message is to alert you that the Case number' + cs.CaseNumber + ' has been deleted. Thank you for contacting us.');
            emails.add(email);
        }
        Messaging.sendEmail(emails);
    }
    

}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Can yoy check the below article . It explains why this issue usually occurs.

https://help.salesforce.com/s/articleView?id=000353740&type=1 (https://help.salesforce.com/s/articleView?id=000353740&type=1)

Thanks,
 
This was selected as the best answer
jaishrijaishri
Hi Sai, Thank you for your help