Saturday, June 13, 2015

Sending email through batch classe for sucess or failed DML operations


Every ran into a situation where you wanted to receive a email with "What happened to the DML operation" did it complete etc etc.

This was accomplished with My fellow developer Piyush Kalra

Here is the code 
 global class BatchClassToUpdateAmountQuot implements Database.Batchable,Database.stateful{
    global  BatchClassToUpdateAmountQuot(){
                // Batch Constructor
     }
     //Declaring the variable of sucesses
  global integer noOfSuccess=0;
     //Declaring the list of error message
  global list errroList= new list();
    global Database.QueryLocator start(Database.BatchableContext BC){
       String Query = 'Select Id From Contacts';
       return Database.getQueryLocator(query);
   }
    global void execute(Database.BatchableContext BC,Listscope){
        //Some funny logic goes here
  
  
        Database.saveResult[]  saveResults;
        
  //This is how you are going to do a dml operation
        saveResults=Database.update(toUpdateOpps,false);
        
        for(Database.saveResult sr:saveResults){
            if(sr.isSuccess()){
                noOfSuccess++;
            }else{
                for(Database.Error err : sr.getErrors()) {
                    
                    errroList.add(err.getMessage());
                }
            }       
        }
        
    }
   global void finish(Database.BatchableContext BC){
        system.debug('Debug');
       List mails = new List();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        //send to
        List sendTo = new List();
        sendTo.add('piyushS.algo@gmail.com');
        mail.setToAddresses(sendTo);
        //sent reply to 
        
        mail.setSenderDisplayName('Info');
        //The email
        mail.setSubject('batch class email');
        String finalBody = '';
        for(String err : errroList){
            finalBody += 'Record failed :'+err+'\n'; 
        
        }
        finalBody += 'RECORDS PROCESSED TOTAL :'+noOfSuccess;
        String body = 'The batch class';
        system.debug('selectedTemplate.HtmlValue'+body);
        mail.setPlainTextbody(finalBody );
                
        //mail.setPlainTextBody(body);
        mails.add(mail);
            
        //End Preparing the Email
        Messaging.sendEmail(mails);
   } 
}