Loading

EmailHeader.triggerUserEmail doesn't prevent email notice from being sent

Fecha de publicación: Oct 13, 2022
Descripción

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. Email notifications are not prevented even if you set DMLOptions.EmailHeader.triggerUserEmail to 'false'. 

Steps to reproduce the issue:

 
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); 
} 
} 
}
3. On an existing case, tick the Change Ownership checkbox and notice that the email notification is sent even when triggerUserEmail=false. 

Note that similar steps can be followed in case of a lead ownership change.
Solución

DMLOptions does not work to prevent email notifications as it only applies to DML calls made after the DML options are applied. So, you would need to generate a list of objects to insert/update and set DMLOptions on them.

 

Workaround: Use of @future method to resolve the issue 

 

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
} 
}
Número del artículo de conocimiento

000385933

 
Cargando
Salesforce Help | Article