Skip to main content

Salesforce

How to Send Emails Using Schedulable Apex ?

Hello Trailblazers,

In this blog post, we will learn how to send reminder Emails using Schedulable Apex Batch Class.

Acceptance Criteria: Write an Apex Batch to send a reminder email to the owner when the Product due is near. Schedule this apex batch to send automatic emails to the owner.

If you want to learn how to write a simple batch class, you can go with this link.

In this example, we’ll develop a batch class that will have a schedulable interface, containing the logic for sending reminder emails to the product owner when the expiry date of the product is approaching. The batch job runs daily and sends one email reminder per day starting from 3 days before the expiry date.

 

So, let’s get started…

Schedulable Batch Apex to Send Email:

public class ProductReminderBatch implements Database.Batchable<SObject>, Schedulable {

    private static final Integer DAYS_BEFORE_EXPIRY = 3;

    public Database.QueryLocator start(Database.BatchableContext context) {
        // Query products with expiry dates in the next 3 days
        Date threeDaysBeforeExpiry = Date.today().addDays(DAYS_BEFORE_EXPIRY);
        String query = 'SELECT Id, Name, Expiry_Date__c, Owner_Email__c FROM Product__c ' +
                       'WHERE Expiry_Date__c = :threeDaysBeforeExpiry';
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext context, List<Product__c> products) {
        List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();

        for (Product__c product : products) {
            // Create an email message for each product
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new String[]{product.Owner_Email__c});
            email.setSubject('Product Expiry Reminder');
            email.setPlainTextBody('Dear Product Owner,\n\nThis is a reminder that the product "' +
                                   product.Name + '" is expiring on ' + product.Expiry_Date__c +
                                   '. Please take necessary actions.\n\nSincerely,\nYour Well Wisher);
            emailsToSend.add(email);
        }

        // Send the emails
        Messaging.sendEmail(emailsToSend);
    }

    public void finish(Database.BatchableContext context) {
        // Perform any post-processing logic if needed
    }

    public void execute(SchedulableContext context) {
        // Implement the scheduling logic here
        ProductReminderBatch batchJob = new ProductReminderBatch();
        Database.executeBatch(batchJob);
    }
}

Let’s break down the things that we did in the above example:

  1. The ProductReminderBatch class implements both the Batchable<SObject> and Schedulable interfaces.
  2. Start() – In the above example, the start method queries products with expiry dates in the next 3 days.
  3. Execute() – Here, the execute method creates an email message for each product and sends the email reminders.
  4. Finish() – The finish method is optional and can be used for any post-processing logic.
  5. Execute() – The execute method is part of the Schedulable interface and is responsible for scheduling the batch job. In this example, it’s calling executeBatch to start the batch job.

 

Now, it comes to scheduling the batch. To schedule this batch job, you can use the Salesforce Developer Console or execute the following anonymous Apex script:

Schedule Batch Apex:

// Schedule the job to run every day at 6.30 AM
String cronExpression = '0 30 6 * * ? *';
System.schedule('ProductReminderBatch', cronExpression, new ProductReminderBatch());

Use the CRON expression as above to schedule the batch . Here, we scheduled the batch to run at 6.30 am daily, starting from 3 days before the expiry date.

If you want to explore more about CRON Expression, then you can go with this link. I’ve explained it in detail.

Another way to schedule a batch is from Setup or Salesforce org User Interface. If you would like to know more, you can go with this link.

 

Conclusion:

In this way, we scheduled a apex batch using CRON Expression to send reminder emails.

 

Stay Tuned !!

References:

  1. Batch Apex in Salesforce

  2. Asynchronous Apex in Salesforce

 

You can also read :

1.An Introduction to Salesforce CPQ
2.Salesforce CPQ and its Key Features
3.Unlocking the Power of AI: Einstein for Developers
4.Revolutionizing Customer Engagement: The Salesforce Einstein Chatbot

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Abhinav Masane

Abhinav Masane is an Associate Technical Consultant at Perficient based in Nagpur. He is a Salesforce Certified Associate and Developer. Abhinav is always keen to learn and explore new technologies.

More from this Author

Follow Us