Print this page

EmailHeader.triggerUserEmail does not prevent the email notification sent when a case or lead owner is changed via Apex code

Knowledge Article Number 000176854
Description When an Apex trigger on Cases or Leads changes the owner of records available in Trigger.new, automatically generated email notifications (case/lead assignment notification) are sent to the assignee. Why can this not be prevented by using setting DMLOptions.EmailHeader.triggerUserEmail to false?

Specifically this is how the problem can be reproduced:

1) Create a test user and set its email address to yours. 
2) Create a custom checkbox called "Change Ownership" on cases to control ownership changes and use the below trigger to reassign the case: 

trigger ChangeOwnership on Case (before insert, before update) { 
Database.DMLOptions dmo = new Database.DMLOptions(); 
dmo.EmailHeader.triggerUserEmail = false; 

for (Case c : Trigger.New){ 
if (c.Change_Ownership__c == true){ 
c.OwnerId='005i0000000QxRg'; // hard code the ID of the test user 
c.Change_Ownership__c = false; 
c.setOptions(dmo); 




2) On an existing case, tick the Change Ownership checkbox and notice that the email notification is sent despite of using triggerUserEmail=false. 

Notice that similar steps can be followed in the case of lead ownership changes.
Resolution The reason why in the above scenario DMLOptions does not work is because it only applies to DML calls made after the DML options are applied. I.e. you would need to generate a list of objects to insert/update and set DMLOptions on them.

 

As a workaround for the scenario shown above, one could use a @future method as the following:

trigger ChangeOwnership_v2 on Case (before update) { 
List<ID> caseIDs = new List<ID>(); 

for (Case c : Trigger.New){ 
if (c.Change_Ownership__c == true){ 
caseIDs.add(c.Id); 



if(caseIDs.size() > 0) { 
CaseHelper.updateOwnership(caseIDs); 



public class CaseHelper { 

@future 
public static void updateOwnership(List<Id> caseIDs) { 
Database.DMLOptions dmo = new Database.DMLOptions(); 
dmo.EmailHeader.triggerUserEmail = false; 

List<Case> casesToUpdate = [select ownerid, change_ownership__c from case where id in :caseIDs]; 

for(Case c : casesToUpdate) { 
c.OwnerId='005i0000000QxRg'; 
c.Change_Ownership__c = false; 


Database.update(casesToUpdate, dmo); // Actual DML operation is performed instead of implicit update

}




promote demote