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
sfdc G 9sfdc G 9 

I am getting two emails from a trigger

Hi All,

I have a before update Trigger and it is sending two emails when changing a case owner. Kindly help me It should send only once.
trigger sendEmailOnOwnerChange on Case (before update)
    Map<Id, Case> map_OldCaseValues = new Map<Id, Case>();
    Map<Id, Case> map_NewCaseValues = new Map<Id, Case>();

    String currentUserId = UserInfo.getUserId();
    Boolean sendMail = false;
    Boolean emailToNewCaseOwner;
    Boolean isEmailToOldAndNewOwner = false;
    for(integer i =0; i<Trigger.New.Size(); i ++)
        if(Trigger.New[i].OwnerId != Trigger.oldMap.get([i].id).OwnerId)
           /*Requirement 443*/
           Trigger.New[i].Number_of_times_Flash_Displayed__c = 0;
           if(Trigger.oldMap.get([i].id).OwnerId!= currentUserId &&[i].OwnerId == currentUserId )
               emailToNewCaseOwner = false;
        new sendEmailOnOwnerChangeController().notificationStatusForInsert(map_NewCaseValues,map_OldCaseValues,emailToNewCaseOwner,isEmailToOldAndNewOwner);                
I put debuglog and verified it triggered two times
Thanks In Advance,
Gururaj BGururaj B
I think you have either the process builder or workflow on Case object (on update) which in turn updating the case. This would lead to the execution of Trigger multiple times. So you are seeing the email multiple times. If it has helped in any ways to solve your problem please mark as best answer
v varaprasadv varaprasad
Hi Deepak,

Try once like below:
if(Trigger.New[i].OwnerId != Trigger.oldMap.get([i].id).OwnerId && trigger.isBefore&&Trigger.isupdate)

or create one stattic variable

public class stopRecursion{
public static boolean runOnce = false; 

if(Trigger.New[i].OwnerId != Trigger.oldMap.get([i].id).OwnerId && stopRecursion.runOnce == false){
  //Do your logic
  stopRecursion.runOnce = True;

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

@For Support: