Expiry notification through email using schedulable class in Salesforce

Expiry notification through email using schedulable class in Salesforce

Sample Code:

Batch Apex Class:


global class expireNotify implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date d = Date.today();
        String soql = ‘SELECT Expiry_Date__c, Name, Email_Address__c FROM Member__c WHERE Expiry_Date__c =: d’;
        return Database.getQueryLocator(soql);
    }
  
    global void execute(Database.BatchableContext bc, List<Member__c> recs) {
        List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
        for(Member__c m : recs) {
            List<String> toAddresses = new List<String>();          
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            toAddresses.add(m.Email_Address__c);
            mail.setToAddresses(toAddresses);
            mail.setSubject(‘Welcome to Sweet 16 Siebel Batch’);
            String messageBody = ‘<html><body>Hi ‘ + m.Name + ‘,<br>Your account Expires today. <br>Kindly contact your administrator.<br><br><b>Regards,</b><br>Magulan D</body></html>’;
            mail.setHtmlBody(messageBody);
            mailList.add(mail);         
        }
        Messaging.sendEmail(mailList);
    }
  
    global void finish(Database.BatchableContext bc) {
    }
}

Schedulable Class:

global class scheduleExpireNotify implements Schedulable {
    global void execute(SchedulableContext sc) {
        expireNotify en = new expireNotify();

        Database.executeBatch(en);
    }
}

Schedule the ‘scheduleExpireNotify’ as mentioned below in App Setup
–> Apex Classes –> Schedule Apex and select
‘s
scheduleExpireNotify‘ class. Check Weekly and select all the days. Give
Start and End dates and Preferred Start time and Click ‘Save’ button.

Leave a Reply