function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
satya ajithsatya ajith 

How to write batch apex class to 'send outbond Emails to all contact Emails' at a time

Abdul KhatriAbdul Khatri
Batch Class
global class ContactEmailUpdateBatch implements Database.Batchable<sObject>
{

   global final String Query;
   
   global ContactEmailUpdateBatch(){
      
       Query='SELECT Email FROM Contact WHERE Email != null';

   }

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

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

        List<Contact> contactsToUpdate = new List<Contact>();  
        EmailManager emailMgr = new EmailManager();
       
        for(Contact contact : scope)
        {
			emailMgr.sendMail(contact.Email, 'Subject', 'Body');
        }      

   }

   global void finish(Database.BatchableContext BC){

   }
}

Email Class
public class EmailManager {
    // Public method
    public void sendMail(String address, String subject, String body) {
        // Create an email message object
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {address};
        mail.setToAddresses(toAddresses);
        mail.setSubject(subject);
        mail.setPlainTextBody(body);
        // Pass this email message to the built-in sendEmail method 
        // of the Messaging class
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
        
        // Call a helper method to inspect the returned results
        inspectResults(results);
    }
    
    // Helper method
    private static Boolean inspectResults(Messaging.SendEmailResult[] results) {
        Boolean sendResult = true;
        
        // sendEmail returns an array of result objects.
        // Iterate through the list to inspect results. 
        // In this class, the methods send only one email, 
        // so we should have only one result.
        for (Messaging.SendEmailResult res : results) {
            if (res.isSuccess()) {
                System.debug('Email sent successfully');
            }
            else {
                sendResult = false;
                System.debug('The following errors occurred: ' + res.getErrors());                 
            }
        }
        
        return sendResult;
    }

}

If it helps please don't foget to mark this best answer
Abdul KhatriAbdul Khatri
It helped?
Abdul KhatriAbdul Khatri
Any feeback?
Abdul KhatriAbdul Khatri
Hello
Abdul KhatriAbdul Khatri
Hello Sir, would that helpful. You seems like you gone?
Abdul KhatriAbdul Khatri
Hello
Abdul KhatriAbdul Khatri
Hello Sir, any feedback on my solution.