Batch apex for sending mail for multiple accounts
Batch Apex is a powerful feature in Salesforce that allows you to execute a set of Apex code in a batch, which can be useful for sending emails to multiple accounts. Here's an example of how you can use Batch Apex to send emails to multiple accounts:
Step 1: Create a Batch Apex Class
Create a new Apex class that extends the Database.Batchable<sObject>
interface. In this example, we'll create a class called SendEmailBatch
.
global class SendEmailBatch implements Database.Batchable<sObject>, Database.Stateful {
global Database.QueryLocator start(Database.BatchableContext BC) {
// Define the query to retrieve the accounts to send emails to
return Database.getQueryLocator('SELECT Id FROM Account WHERE IsEmailEnabled = true');
}
global void execute(Database.BatchableContext BC, List<sObject> scope) {
// Loop through the accounts in the scope
for (Account account : (List<Account>)scope) {
// Send an email to the account
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSubject('Test Email');
mail.setBody('This is a test email');
mail.setToList(new List<String>{account.Email});
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}
}
global void finish(Database.BatchableContext BC) {
// No-op
}
}
Step 2: Create a Job
Create a new job that will execute the SendEmailBatch
class. You can do this by clicking on the "New" button in the "Batch Jobs" section of the Setup menu, and then selecting "Batch Apex" as the job type.
Step 3: Configure the Job
Configure the job by specifying the SendEmailBatch
class as the batch class, and setting the query to retrieve the accounts to send emails to. You can also set the batch size and the number of concurrent executions.
Step 4: Execute the Job
Click the "Schedule" button to execute the job. The job will run in the background and send emails to the accounts specified in the query.
Tips and Variations
- You can customize the email template and content by using the
Messaging.SingleEmailMessage
class. - You can also use the
Messaging.EmailMessage
class to send emails with attachments. - You can use the
Database.getQueryLocator
method to retrieve a list of accounts to send emails to, or use a custom query to retrieve the accounts. - You can use the
Database.executeBatch
method to execute the batch job manually, rather than scheduling it. - You can use the
Database.getBatchable
method to retrieve the batch job and its status.