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)

    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.setSubject('Test mail');
        mail1.setPlainTextBody('this is a test mail');

    global void finish(Database.BatchableContext BC) {
  • 1
    N.B. - use public, not global; also the for loop can iterate over scope; you don't need ContactList
    – cropredy
    May 27, 2021 at 15:54

1 Answer 1


Move your Messaging.SingleEmailMessage mail1=new Messaging.SingleEmailMessage(); line to inside the for(Contact a:ContactList)... loop to create a new message instance to use every time.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .