+ Start a Discussion
Whitney Klein 10Whitney Klein 10 

Sending an email template using a trigger

Hello, I would like to send out an email alert to users when an account has not ordered in 75 days. I have a formula field that tracks the Days Since Last Order. The formula will not trigger the workflow rule I created and I believe I need to write a trigger. I am a huge newbie so any help is greatly appreciated!! 
@Karanraj@Karanraj
The trigger also event based i.e., if there is any DML operation performed then only it will perform the code logic.
So you have to go with the Schedule apex and Batch apex class. 

1. Batch Apex Class:
Write your logic to fetch the account record sent email in the batch class. The batch class can handle a large number of records.
Below is the sample structure of batch apex class. For more details on the batch apex class, check this link -  https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm
global class SendEmailToAccount implements Database.Batchable<sObject>{
   
   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator('Select Id,Name from Account where DaysSinceLastOrder__c >= 75');
   }

   global void execute(Database.BatchableContext BC, 
                       List<sObject> scope){
      for(Sobject s : scope)
      {
        //Write your logic to send email
      }  
     
   }
   global void finish(Database.BatchableContext BC){

   }

}
Sending email in apex class - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm

2. Scheduled Apex class
Scheduled apex class is to run the code logic at a particular time interval on daily or monthly or weekly basis. 
Schedule the above batch to run daily at the particular time. Check this link for more details - https://developer.salesforce.com/docs/atlas.en-us.200.0.apexcode.meta/apexcode/apex_scheduler.htm
global class scheduledBatchable implements Schedulable {
   global void execute(SchedulableContext sc) {
      SendEmailToAccount emailToAccount = new SendEmailToAccount(); 
      database.executebatch(emailToAccount);
   }
}