batch class will accept a list of SingleEmailMessage objects and send the emails in its execute method.


/global class EmailBatchClass implements Database.Batchable {
    
    // Define a list to hold email messages
    private List emails;

    // Constructor to pass the list of email messages to the batch class
    public EmailBatchClass(List emails) {
        this.emails = emails;
    }

    // Start method, returns the list of emails to be processed
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Id FROM Contact WHERE Id = '12345']); // Dummy SOQL as SingleEmailMessage is not queryable
    }

    // Execute method, processes the email sending
    global void execute(Database.BatchableContext BC, List scope) {
        if (emails != null && !emails.isEmpty()) {
            try {
                Messaging.sendEmail(emails);
            } catch (Exception e) {
                // Handle any exceptions during email sending
                System.debug('Error sending emails: ' + e.getMessage());
            }
        }
    }

    // Finish method
    global void finish(Database.BatchableContext BC) {
        System.debug('Batch processing finished.');
    }
}




public class EmailSenderClass {
    
    public void sendBatchEmails() {
        // Create a list of SingleEmailMessage objects
        List emailMessages = new List();

        // Populate the list with emails
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new List{'example@example.com'});
        email.setSubject('Test Email');
        email.setPlainTextBody('This is a test email.');
        emailMessages.add(email);

        // Instantiate and execute the batch class with the email list
        EmailBatchClass batch = new EmailBatchClass(emailMessages);
        Database.executeBatch(batch, 1); // Passing 1 as batch size since we're not processing multiple chunks
    }
}


batch class will accept a list of SingleEmailMessage objects and send the emails in its execute method.  batch class will accept a list of SingleEmailMessage objects and send the emails in its execute method. Reviewed by dasfrogpractice on 04:50 Rating: 5

No comments:

Theme images by mariusFM77. Powered by Blogger.
Youtube Channel Image
Dasfrog Subscribe To watch more Salesforce Training
Subscribe