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
srinivas pulipatisrinivas pulipati 

How to send e mail for all record owners

Hi all i want a trigger if i change owner of a particular record then we need to notify all the record owners of that object records if any one helps i am very thankfull you
Bhanu MaheshBhanu Mahesh
Hi Srinivas,

Try below code. I have implemented for Account object.
Modify as per your requirement
 
trigger sendEmailToOwners on Account(after update){
    Boolean ownerChanged = false;
    List<String> allEmails = new List<String>();
    Set<Id> userIds = new Set<Id>();
    Map<Id,String> mapUserNameWithId = new Map<Id,String>();
    for(Account acc: trigger.new){
        if(acc.OwnerId != trigger.oldMap.get(acc.Id).OwnerId){
            ownerChanged = true;
            userIds.add(acc.OwnerId);
            userIds.add(trigger.oldMap.get(acc.Id).OwnerId);
        }
    }
    if(ownerChanged){
            List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
            for(User usr : [SELECT Id,Email,Name FROM User WHERE Id IN :userIds]){
                    mapUserNameWithId.put(usr.Id,usr.Name);
            }
            for(AggregateResult agrr :[SELECT Owner.Email From Account Group by Owner.Email]){
                        String toEmail = String.valueOf(agrr.get('Email'));
                        allEmails.add(toEmail);
            }
            if(!allEmails.isEmpty()){
                    for(Account acc: trigger.new){
                        if(acc.OwnerId != trigger.oldMap.get(acc.Id).OwnerId){
                            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                            mail.setToAddresses(allEmails);
                            mail.setSubject('Owner Changed for Account : ' + acc.Name);
                            mail.setPlainTextBody('Owner of Account: ' + acc.Name + ' Changed from ' + mapUserNameWithId.get(trigger.oldMap.get(acc.Id).OwnerId) + ' to ' +mapUserNameWithId.get(acc.OwnerId));
                            String body = 'Owner of Account: <b>' + acc.Name;
                            body += '</b> Changed from <b>' + mapUserNameWithId.get(trigger.oldMap.get(acc.Id).OwnerId);
                            body += '</b> to <b>' + mapUserNameWithId.get(acc.OwnerId)  + '</b>';
                            mail.setHtmlBody(body);
                            mails.add(mail);
                        }
                    }
            }
            if(!mails.isEmpty()){
                Messaging.sendEmail(mails);
            }
    }
}

Mark this as "SOLVED" if your query is answered.

Thanks & Regards,
Bhanu Mahesh Gadi
srinivas pulipatisrinivas pulipati
Thank u BanuMahesh