• VSrinivasan
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies

Hi,

 

I have written a batch class to send an email when there is a mismatch between two fields, In Execute method i have added the list of records having a mismatch in a list. I need to send the list as an attachment in a single mail. In the below code i am sending the mail in execute method, so for each and every mismatch record i am getting individual mail. But instead i need the whole list to be inserted in the mail body or as an attachment and send only one mail. Mail should not be sent for individual records.

 

Please let me know how to send only one mail with the list of records inserted in mail body or as an attahment and also let me know how to pass the list of records present in execute method to finish method.

 

PFB my sample code,

 

global class SendMail implements Database.Batchable<SObject>

{
List<User> usersList = new List<User>();


global Database.QueryLocator start(Database.BatchableContext BC)

{

return Database.getQueryLocator('select id,Name,EmployeeNumber,NewEmail__c,Testing__c,Email from User');

}

global void execute(Database.BatchableContext BC,List<Sobject> scope)

{

for(Sobject s : scope)

{
    User a = (User)s;
    if(a.EmployeeNumber != a.Testing__c || a.Email != a.NewEmail__c )
    usersList.add(a);
}

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

String[] toAddresses = new String[] {'Srinivasanece@gmail.com'};

mail.setToAddresses(toAddresses);

mail.setSubject('Apex Batch Job is done');

For(User p:usersList){

mail.setPlainTextBody('The batch Apex job processed'+p.id);

}

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

}

 

global void finish(Database.BatchableContext BC)

{
/*Mail to User mentioned in the "toAddress"*/   
/*Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

String[] toAddresses = new String[] {'srinivasanece90@gmail.com'};

mail.setToAddresses(toAddresses);

mail.setSubject('Apex Batch Job is done');

mail.setPlainTextBody('The batch Apex job processed');

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
*/
}

}