Skip to main content
edited tags; edited tags
Link
pchittum
  • 19.8k
  • 5
  • 57
  • 99
Source Link

How to Send email to multiple user from batch apex

I am trying to create a batch that will run every day and will find the contacts which match the criteria. at the moment the code I have written is sending email to the same email address (time the contact match criteria)

I want to send an email to that specifc user which the records belong not to same user agaian and again. Below is my code.

 global class RTS implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id,Email,RTS_Count__c FROM Contact WHERE RTS_Count__c = 1 and Email !=null';
        return Database.getQueryLocator(query);
    }
    global String body='';
    global List<Contact> ContactList = new List<Contact>();
   global void execute(Database.BatchableContext BC, List<Contact> scope) {
     for(Contact a : scope)
     {
         ContactList.add(a);
     }

    List<Messaging.SingleEmailMessage> lstEmail = new List<Messaging.SingleEmailMessage>();
    Messaging.SingleEmailMessage mail1=new Messaging.SingleEmailMessage();
  

    for(Contact a:ContactList){
        String[] toadd=new String[]{a.Email};
        string b =  'hello' ; 
        body += b ;
        mail1.setToAddresses(toadd);
        mail1.setSubject('Test mail');
        mail1.setPlainTextBody('this is a test mail');
        mail1.setHtmlBody(body);
        lstEmail.add(mail1);
    }
    System.debug(body);
       Messaging.SendEmail(lstEmail);
}  

    global void finish(Database.BatchableContext BC) {
    
    }
}