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
Shruthi MN 88Shruthi MN 88 

Email notification on Case trigger

Develop a trigger that sends an email notification to the account owner when a high-priority case is created or updated.

I have written the below code but email is not getting fired 

public class CaseEmailNotificationHandler {
    public static void sendEmailNotifications(List<Case> casesToUpdate) {
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
 
        // Collect Account Owner Ids for high-priority cases and fetch User information
        Map<Id, User> accountOwners = new Map<Id, User>();
        
        for (Case updatedCase : casesToUpdate) {
            if (updatedCase.Priority == 'High') {
                Id ownerId = updatedCase.Account.OwnerId;
                
                // Check if the ownerId has not been processed already
                if (!accountOwners.containsKey(ownerId)) {
                    List<User> owners = [SELECT Id, Name, Email FROM User WHERE Id = :ownerId LIMIT 1];
                    if (!owners.isEmpty()) {
                        accountOwners.put(ownerId, owners[0]);
                    } else {
                        System.debug('No User found for ownerId: ' + ownerId);
                    }
                }
 
                User accountOwner = accountOwners.get(ownerId);

                if (accountOwner != null && !String.isBlank(accountOwner.Email)) {
                    // Create email message
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    email.setSubject('High-Priority Case Notification');
                    email.setHtmlBody('<p>Hello, ' + accountOwner.Name + ',</p>' +
                                      '<p>A high-priority case has been created or updated. Please review the details.</p>' +
                                      '<p>Case Number: ' + updatedCase.CaseNumber + '</p>' +
                                      '<p>Case Subject: ' + updatedCase.Subject + '</p>' +
                                      '<p>Priority: ' + updatedCase.Priority + '</p>' +
                                      '<p>Thank you!</p>');
                    email.setTargetObjectId(accountOwner.Id);
                    email.setSaveAsActivity(false);
                    emailMessages.add(email);
                } else {
                    System.debug('Email not sent due to missing or invalid recipient for case Id: ' + updatedCase.Id);
                }
            }
        }
         
        if (!emailMessages.isEmpty()) {
            List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(emailMessages);
            for (Messaging.SendEmailResult result : sendResults) {
                if (!result.isSuccess()) {
                    System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
                }
            }
        }
    }
}
trigger CaseEmailNotificationTrigger on Case (after insert, after update) {
    if (Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)) {
        CaseEmailNotificationHandler.sendEmailNotifications(Trigger.new);
    }
}
Best Answer chosen by Shruthi MN 88
CharuDuttCharuDutt
Hii Shrithi
Try Below Code I've Made Changes
public class CaseEmailNotificationHandler {
   public static void sendEmailNotifications(List<Case> casesToUpdate) {
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
        
        // Collect Account Owner Ids for high-priority cases and fetch User information
        Map<Id, Case> accountOwners = new Map<Id, Case>();
        
        for (Case updatedCase : casesToUpdate) {
            if (updatedCase.Priority == 'High') {
                if(updatedCase.AccountId != null){
                    accountOwners.Put(updatedCase.AccountId,updatedCase);
                }
            }
        }
        List<Account> lstAccount = [SELECT Id, Name, Owner.Email, Owner.Name FROM Account WHERE Id In :accountOwners.KeySet()];
        For(Account oAccount : lstAccount){
            case oCase = accountOwners.get(oAccount.Id);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setSubject('High-Priority Case Notification');
            email.setHtmlBody('<p>Hello, ' + oAccount.Owner.Name + ',</p>' +
                              '<p>A high-priority case has been created or updated. Please review the details.</p>' +
                              '<p>Case Number: ' + oCase.CaseNumber + '</p>' +
                              '<p>Case Subject: ' + oCase.Subject + '</p>' +
                              '<p>Priority: ' + oCase.Priority + '</p>' +
                              '<p>Thank you!</p>');
            
            
            email.setToAddresses(new list<String>{oAccount.Owner.Email});
            email.setSaveAsActivity(false);
            emailMessages.add(email);
        }
        
        if (!emailMessages.isEmpty()) {
            List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(emailMessages);
            for (Messaging.SendEmailResult result : sendResults) {
                if (!result.isSuccess()) {
                    System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
                }
            }
        }
    }
}

Please Mark It As Best Answer If It Helps
Thank You!

 

All Answers

CharuDuttCharuDutt
Hii Shruthi
Try Below Code
public class CaseEmailNotificationHandler {
   public static void sendEmailNotifications(List<Case> casesToUpdate) {
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
        
        // Collect Account Owner Ids for high-priority cases and fetch User information
        Map<Id, Case> accountOwners = new Map<Id, Case>();
        
        for (Case updatedCase : casesToUpdate) {
            if (updatedCase.Priority == 'High') {
                if(updatedCase.AccountId != null){
                    accountOwners.Put(updatedCase.AccountId,updatedCase);
                }
            }
        }
        List<Account> lstAccount = [SELECT Id, Name, Owner.Email, Owner.Name FROM Account WHERE Id In :accountOwners.KeySet()];
        For(Account oAccount : lstAccount){
            case oCase = accountOwners.get(oAccount.Id);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setSubject('High-Priority Case Notification');
            email.setHtmlBody('<p>Hello, ' + oAccount.Owner.Name + ',</p>' +
                              '<p>A high-priority case has been created or updated. Please review the details.</p>' +
                              '<p>Case Number: ' + oCase.CaseNumber + '</p>' +
                              '<p>Case Subject: ' + oCase.Subject + '</p>' +
                              '<p>Priority: ' + oCase.Priority + '</p>' +
                              '<p>Thank you!</p>');
            email.setTargetObjectId(oAccount.Id);
            
            email.setToAddresses(new list<String>{oAccount.Owner.Email});
            email.setSaveAsActivity(false);
            emailMessages.add(email);
        }
        
        if (!emailMessages.isEmpty()) {
            List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(emailMessages);
            for (Messaging.SendEmailResult result : sendResults) {
                if (!result.isSuccess()) {
                    System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
                }
            }
        }
    }
}

Please Mark It As Best Answer If It Helps
Thank You!


 
Shruthi MN 88Shruthi MN 88
I am getting the attached errorUser-added image
CharuDuttCharuDutt
Hii Shrithi
Try Below Code I've Made Changes
public class CaseEmailNotificationHandler {
   public static void sendEmailNotifications(List<Case> casesToUpdate) {
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
        
        // Collect Account Owner Ids for high-priority cases and fetch User information
        Map<Id, Case> accountOwners = new Map<Id, Case>();
        
        for (Case updatedCase : casesToUpdate) {
            if (updatedCase.Priority == 'High') {
                if(updatedCase.AccountId != null){
                    accountOwners.Put(updatedCase.AccountId,updatedCase);
                }
            }
        }
        List<Account> lstAccount = [SELECT Id, Name, Owner.Email, Owner.Name FROM Account WHERE Id In :accountOwners.KeySet()];
        For(Account oAccount : lstAccount){
            case oCase = accountOwners.get(oAccount.Id);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setSubject('High-Priority Case Notification');
            email.setHtmlBody('<p>Hello, ' + oAccount.Owner.Name + ',</p>' +
                              '<p>A high-priority case has been created or updated. Please review the details.</p>' +
                              '<p>Case Number: ' + oCase.CaseNumber + '</p>' +
                              '<p>Case Subject: ' + oCase.Subject + '</p>' +
                              '<p>Priority: ' + oCase.Priority + '</p>' +
                              '<p>Thank you!</p>');
            
            
            email.setToAddresses(new list<String>{oAccount.Owner.Email});
            email.setSaveAsActivity(false);
            emailMessages.add(email);
        }
        
        if (!emailMessages.isEmpty()) {
            List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(emailMessages);
            for (Messaging.SendEmailResult result : sendResults) {
                if (!result.isSuccess()) {
                    System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
                }
            }
        }
    }
}

Please Mark It As Best Answer If It Helps
Thank You!

 
This was selected as the best answer
Shruthi MN 88Shruthi MN 88
I have modifed the code and used LastModified date in the query editer records are getting displayed but when I run the class in anynomous window only 6 line is getting executed.
global class UpdateLeadStatusBatch implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {
        //DateTime thirtyDaysAgo = System.now().addDays(-2);
        String query = 'SELECT Id, OwnerId FROM Lead WHERE LastModifiedDate <= N_DAYS_AGO:1 AND Status != \'closed lost\'';
        system.debug(query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Lead> scope) {
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
        List<Lead> leadsToUpdate = new List<Lead>();
        map<Id,Lead> managerIds = new map<Id,Lead>();
 System.debug('Number of leads to update: ' + leadsToUpdate.size());
        for (Lead olead : scope) {
            olead.Status = 'closed lost';
            leadsToUpdate.add(olead);
            if (olead.OwnerId!= null) {
                managerIds.put(olead.OwnerId,oLead);
               
            }
        }

        update leadsToUpdate;

        // Send Notification to Managers
        // Using Email Services to send email notifications
        if (!managerIds.isEmpty()) {
            list<User> lstmanagerUser = [SELECT Id, Email, ManagerId, Manager.email, Manager.Name FROM User WHERE Id In :managerIds.KeySet()];
            system.debug('Manager' +lstmanagerUser);
            for(User managerUser : lstmanagerUser){

                // Construct and send email to the manager
                if (managerUser != null && !String.isBlank(managerUser.Email)) {
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    email.setSubject('Lead Status Update');
                    email.setHtmlBody('<p>Hello, ' + managerUser.Manager.Name + ',</p>' +
                                      '<p>The status of some leads has been updated to "Closed - Lost" due to inactivity.</p>' +
                                      '<p>Thank you!</p>');
                    email.setTargetObjectId(managerUser.Id);
                    email.setToAddresses(new list<String>{managerUser.Manager.email});
                    email.setSaveAsActivity(false);
                    emailMessages.add(email);
                }
            }
        }

            if (!emailMessages.isEmpty()) {
                List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(emailMessages);
                for (Messaging.SendEmailResult result : sendResults) {
                    if (!result.isSuccess()) {
                        System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
                    }
                }
            }
    }

    global void finish(Database.BatchableContext BC) {
        // Any logic you want to execute after the batch finishes
    }
    
}