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
SKollcakuSKollcaku 

Send automatic Email to user when an Apex job terminates its execution

Hi everyone,

We have an Apex job/batch which executes each week and deletes all Contact records whith a certain condition (let suppose, ActivationDate__c older than 24-months).

How should I edit this Apex job in order to send automatically an Email to a Salesforce user whenever it finishes to comunicate the result (such as: success or failure/exception)?

 

Thank you so much,

Skender

Best Answer chosen by SKollcaku
Gian Piere VallejosGian Piere Vallejos
On a Batch, we can use the finish method "to send confirmation emails or execute post-processing operations". 

For example: 
global class BatchClass implements Database.Batchable<sObject>{

   global BatchClass(){ //Constructor
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
        //Start method
   }

   global void execute(Database.BatchableContext BC, List<sObject> scope){
        //Execute method
    }

   global void finish(Database.BatchableContext BC){
        // Get the ID of the AsyncApexJob representing this batch job
        // from Database.BatchableContext.
        // Query the AsyncApexJob object to retrieve the current job's information.
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Sharing Recalculation ' + a.Status);
        mail.setPlainTextBody
        ('The batch Apex job processed ' + a.TotalJobItems +
        ' batches with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
   }
}

Reference: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm" target="_blank

All Answers

Gian Piere VallejosGian Piere Vallejos
On a Batch, we can use the finish method "to send confirmation emails or execute post-processing operations". 

For example: 
global class BatchClass implements Database.Batchable<sObject>{

   global BatchClass(){ //Constructor
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
        //Start method
   }

   global void execute(Database.BatchableContext BC, List<sObject> scope){
        //Execute method
    }

   global void finish(Database.BatchableContext BC){
        // Get the ID of the AsyncApexJob representing this batch job
        // from Database.BatchableContext.
        // Query the AsyncApexJob object to retrieve the current job's information.
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Sharing Recalculation ' + a.Status);
        mail.setPlainTextBody
        ('The batch Apex job processed ' + a.TotalJobItems +
        ' batches with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
   }
}

Reference: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm" target="_blank
This was selected as the best answer
Danish HodaDanish Hoda
Hi Skender,
Firstly, you need to abort the process to modify anything in the running class, then you can add the logic of sending mails in your finish method of the batch Apex.