function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Satyanarayana.GSatyanarayana.G 

Send email from Batch Apex

Hi,

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,
Satya
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';
         Emailmessage.setHtmlBody(Message);
         emailMsgList.add(Emailmessage);
         if(emailMsgList.size() > 0){
         //Sent email
         Messaging.sendEmail(emailMsgList);
         system.debug('Email is sent Successfully.');
}
Hope it will help you.
Regards,
Ajay
Satyanarayana.GSatyanarayana.G
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});
            email.setSaveAsActivity(false);
            email.setTargetObjectId(ta.OwnerId);
            email.setTemplateId(emailTemplate.Id);
            email.setWhatId(ta.Id);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        }
    }  
    global void finish(Database.BatchableContext BC)
    {
    }
}

Thank you,
Satya