global class NotifyBatch2 implements Database.Batchable<sObject>,Database.Stateful {
/public string query = 'select Id, name,Status__c,CreatedDate from MR_Product__c where Status__c= \'Pending Submission\' And CreatedDate=System.today()-CreatedDate>24';
datetime dt = System.now()-1;
public string query = 'select Id, name,Status__c,CreatedDate,Materials_Meeting_Date__c,Materials_Due_Date__c,CreatedBy.Email,Submitter__c,Book_Coverage__c,Notes__c,Materials_Request_Organization__c from MR_Product__c where Status__c=\'Pending Submission\'';
//And CreatedDate >:dt';
public transient List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
global database.querylocator start(Database.BatchableContext BC)
{
System.debug('CheckRecords:' + query);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, Sobject[] scope)
{
EmailTemplate emailTemplate = [select Id, Body from EmailTemplate where DeveloperName = 'BOOK_REQUEST_Template'];
for (MR_Product__c item : (List<MR_Product__c>)scope) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string MatDueDate = string.valueOfGmt(item.Materials_Due_Date__c);
string MatMeetingDate = string.valueOfGmt(item.Materials_Meeting_Date__c);
string body = emailTemplate.body;
body = body.replace('{!MR_Product__c.Submitter__c}', item.Submitter__c);
body = body.replace('{!MR_Product__c.Materials_Request_Organization__c}', item.Materials_Request_Organization__c);
body = body.replace('{!MR_Product__c.Materials_Due_Date__c}', MatDueDate );
body = body.replace('{!MR_Product__c.Materials_Meeting_Date__c}', MatMeetingDate);
if(item.Notes__c!=null && item.Notes__c!=''){
body = body.replace('{!MR_Product__c.Notes__c}', item.Notes__c);
}
if(item.Book_Coverage__c!=null && item.Book_Coverage__c!=''){
body = body.replace('{!MR_Product__c.Book_Coverage__c}', item.Book_Coverage__c);
}
email.setToAddresses(new String[] {item.createdby.Email});
email.setSaveAsActivity(false);
email.setPlainTextBody(body);
//email.setTargetObjectId(item.id);
email.setTemplateId(emailTemplate.Id);
//email.setWhatId(item.Id);
system.debug('Checkemails' + email);
mails.add(email);
// Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
global void finish(Database.BatchableContext BC) {
Messaging.sendEmail(mails);
}
}
I'm trying to execute this batch apex class. All I want is to do is send emails in the finish method but whenever I declare the list (mails) at global level a null pointer exception is thrown. Find the error message below:
Class.MaterialRequestNotifyBatch2.execute: line 58, column 1
on line number 58 I have the following code: mails.add(email);