Monday, November 9, 2015

Send email on a Apex batch completion




    global void finish(Database.BatchableContext bc) {
        AsyncApexJob job = [SELECT
                                Id, Status,  NumberOfErrors, JobItemsProcessed,
                                TotalJobItems, CompletedDate, ExtendedStatus, ApexClass.name,
                                CreatedBy.Email,  CreatedBy.Name
                            FROM
                                AsyncApexJob
                            WHERE
                                Id =:bc.getJobId()];
       
        //if no errors
        if(job.NumberOfErrors<=0) { return; }
       
        String body = '';
        body += 'Status : '+job.Status+' \r\n' ;
        body += 'Number Of Errors : '+job.NumberOfErrors+' \r\n' ;
        body += 'JobItems Processed : '+job.JobItemsProcessed+' \r\n' ;
        body += 'Total Job Items : '+job.TotalJobItems+' \r\n' ;
        body += 'Completed Date : '+job.CompletedDate+' \r\n' ;
        body += 'Extended Status : '+job.ExtendedStatus+' \r\n' ;
        body += 'Apex Class Name : '+job.ApexClass.name+' \r\n' ;
        body += 'Created By Email : '+job.CreatedBy.Email+' \r\n' ;
        body += 'Created By Name : '+job.CreatedBy.Name+' \r\n' ;
           
        sendNotificationEmail(body, job.CreatedBy.Email);
    }
   
    private static void sendNotificationEmail(String body, String to){
        String emailAddress = 'hasantha@gmail.com';
        // Send an email to the Apex job's submitter on failure.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {emailAddress};

        mail.setToAddresses(toAddresses);
        mail.setSubject('Batch Excecustion Complete');
        mail.setUseSignature(false);
        mail.setPlainTextBody(body);
        try{
            Messaging.reserveSingleEmailCapacity(toAddresses.size());
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
        catch(System.HandledException e){}
        catch(System.NoAccessException e){}
    }

No comments:

Post a Comment