I want to prevent sandbox environments from sending Workflow emails to the "Additional Emails" specified in Email Alerts using the Metadata API in Apex.
I tried using the Tooling API, but it only allows metadata retrieval and doesn’t support updates. After researching, I found that the Metadata API might help achieve this. However, I haven’t been able to find a clear solution for this use case.
I have created below Apex class to retrieve and update CCEmail using Metadata API with the help of MetadataService class. Please have a look in the code here:
public class UpdateCCEmail { public void updateEmailAlertCC(String emailAlertFullName, List<String> newCcEmails) { // Step 1: Create MetadataService instance MetadataService.MetadataPort service = new MetadataService.MetadataPort(); // Use Named Credential directly; this assumes you have 'MetadataAPI' defined correctly. service.endpoint_x = 'callout:MetaNameCred/services/Soap/m/58.0'; // Use the appropriate version // Step 2: Prepare the session header (if necessary) service.SessionHeader = new MetadataService.SessionHeader_element(); service.SessionHeader.sessionId = UserInfo.getSessionId(); // Step 3: Read the existing EmailAlert metadata MetadataService.IReadResult readResult = service.readMetadata('WorkflowAlert ', new String[] { emailAlertFullName }); if (readResult == null || readResult.getRecords().size() == 0) { System.debug('No records found for the specified Email Alert: ' + emailAlertFullName); return; } // Step 4: Cast the metadata to EmailAlert type MetadataService.WorkflowAlert emailAlert = (MetadataService.WorkflowAlert) readResult.getRecords()[0]; // Step 5: Update the CC Emails emailAlert.ccEmails = newCcEmails; // Step 6: Prepare the update request as Metadata MetadataService.Metadata[] updateRequest = new MetadataService.Metadata[] { emailAlert }; // Step 7: Perform the update call with the correct parameter MetadataService.SaveResult[] saveResults = service.updateMetadata(updateRequest); // Step 8: Check for success for (MetadataService.SaveResult saveResult : saveResults) { if (saveResult.success) { System.debug('Email Alert updated successfully: ' + emailAlertFullName); } else { System.debug('Failed to update Email Alert: ' + saveResult.errors[0].message); } } } } I came across similar issues posted by others:
How to prevent emails to 'Aditional Email' on email alerts
Preventing sandbox from sending Workflow emails to "Additional Emails"
However, none of these discussions provide a concrete solution.
Could anyone suggest how to programmatically mask, remove, or disable these alerts in a sandbox?