+ Start a Discussion

Send email from Batch Apex


I would like to send emails to record owners whose records have not been touched since the last 30 days. I have written a batch job to query the records which have not been modified since the last 30 days. Now I would like to send email to record owners. 

Thank you,
Ajay K DubediAjay K Dubedi
Hi Satya,
You have to modify your batch class and make a list of all record owner whose record are not modified in last 30 days. In that list, you add the email of record owner and send an email to that list.
Messaging.SingleEmailMessage Emailmessage = new Messaging.SingleEmailMessage();
         Emailmessage.toaddresses = listofrecordowner;
         Emailmessage.subject=’list not modified’';
         String Message = 'To whom it may concern, <br/>';
         Message += 'Below is a list of the record that still need to be updated’;          
          Message += Thank you';
         if(emailMsgList.size() > 0){
         //Sent email
         system.debug('Email is sent Successfully.');
Hope it will help you.
Hi Ajay, 

Thanks for your response. I have written the below batch job. Not sure if this correct. 
global class InactiveApplication implements Database.Batchable<sObject>
    global Database.QueryLocator start(Database.BatchableContext BC)
        String query = 'Select Id, Name, Owner.Email from Trade_Ally_Account__c where Stage__c = 'Prospecting' and LastModifiedDate = LAST_N_DAYS:31';
        return Database.getQueryLocator(query);
    global void execute(Database.BatchableContext BC, List<Trade_Ally_Account__c> scope)
        EmailTemplate emailTemplate = [select Id, Body from EmailTemplate where DeveloperName = 'Update_Service_Request'];
        for(Trade_Ally_Account__c ta : (List<Trade_Ally_Account__c>)scope) {
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new String[] {ta.Owner.Email});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    global void finish(Database.BatchableContext BC)

Thank you,