0

i have created (my first) batch apex class to set leads that where not touched for over a year to 'automatically closed' and when testing it updates the records correctly. However it does not send out emails to the person who created the record, any help? Thanks in advance

P.s. Any comments on improving my code or alternative ways of doing this are appreciated.

Batch Apex class:

global class AutomaticallyClosedLeads implements Database.Batchable<sObject> {
  private String query = 'SELECT ID, Status from Lead WHERE (Status = \'Open - Not Contacted\' OR ' + 'Status = \'Working - Contacted\') AND ' + 'batchApexTestField__c <= LAST_N_DAYS:365';

  global Database.QueryLocator start(Database.BatchableContext BC)  {
    return Database.getQueryLocator(query);
  }

  global void execute(Database.BatchableContext bc, List<Lead> scope){
    List<Lead> leads = new List<Lead>();
    for (Lead lead : scope) {
        lead.Status = 'Automatically closed';
        leads.add(lead);
    }
    update leads;
 }
  global void finish(Database.BatchableContext bc) {
    AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
        TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :BC.getJobId()];

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
    mail.setSubject('Leads set to automatically closed ' + a.Status);
    mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
  }    
}

Scheduled Apex Class:

global class scheduledLeadUpdate implements Schedulable {
   global void execute(SchedulableContext sc) {
      AutomaticallyClosedLeads acl = new AutomaticallyClosedLeads();
      database.executebatch(acl);
   }
}
4
  • check 'email deliverability' settings in setup. And is it not possible through time dependent workflow instead of batch class?
    – S B
    Apr 6, 2017 at 11:06
  • Yes it is possible but by using a time dependent workflow you are not able to convert leads because of it. Thanks for your answer though! Apr 6, 2017 at 11:08
  • Try running your mail sending code from the dev console by hardcoding the values. You can quickly check to see if it is an issue with limits this way. Check this site for Email limits:developer.salesforce.com/docs/…. Also, it is a good practice to use configuration for sending emails. In this case, you could create an Email alert to run on updates of Lead?
    – SF Learner
    Apr 7, 2017 at 1:56
  • Hey @ShaliniMendu, i'll just let this batch run and then send an Email alert through configuration. Thanks! Apr 11, 2017 at 7:20

0

You must log in to answer this question.

Browse other questions tagged .