Find your content:

Search form

You are here

Scheduling Emails in Apex

 
Share

I need to send emails based on the Number of Days.....Say suppose in my

Policy1---- Send Email should be 10 days Before Due Date & in my

Policy2----Send Email should be 5 days After Due Date...

So accordingly on the selected policy I need to Schedule the email.How can I get with Apex

Answers with examples are much appreciated


Attribution to: Eagerin Sf

Possible Suggestion/Solution #1

I would think that you would need a schedulable (implements Schedulable interface) Batch Apex class that runs daily and checks the Due Date. When the Due Date is either 10 or 5 days before/after as stipulated above, send the email. I have made the assumption that you will also be sending your emails singularly via apex and that you know how to do that.

So, something like this should give you a good start:

global class InvoiceSenderBatch implements Database.Batchable<SObject>, Database.Stateful, Schedulable
    {

        global void execute( SchedulableContext SC )
        {
          // check to see if available slots first, otherwise re-schedule
          InvoiceSenderBatch batch = new InvoiceSenderBatch();
          Database.executeBatch( batch, 1 );
        }

        global Database.QueryLocator start(Database.BatchableContext BC)
        {
            Date datePlus10 = System.today().addDays( 10 );

            String query = 
                'Select Id, ' +
                '   Name, ' +
                'From ' +
                '   c2g__codaInvoice__c ' +
                'Where ' +
                '   c2g__InvoiceDate__c = :datePlus10 ' ;
            }

            return Database.getQueryLocator(query);
        }

        global void execute(Database.BatchableContext BC, List<SObject> scope)
        {           
          for( Sobject invoice : scope )
          {
            emailInvoice( invoice );
            invoice.put( 'Emailed__c', System.today() );
          }
          update scope;
        }


        global void finish(Database.BatchableContext BC)
        {
          // do something interesting
        }
    }

Attribution to: Phil Hawthorn
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/5646

My Block Status

My Block Content