+ Start a Discussion
ApexNewbie77ApexNewbie77 

Sending email alert 60 days before a date field

Hello,
I am trying to create an apex class that will send an email alert 60 days and 45 days before a contract end date. Here are the requirements:
On the account object, there is a date field called, Contract_End_Date__c. An alert must be sent to a user 60 days and 45 days before the Contract_End_Date__c. An alert is sent to one person when the Contract_Amount__c is greater than or equal to 2500 and to a different person when the Contract_Amount__c is less than 2500.

My idea was to create an apex class with a scheduler class and have it run every night to check if Today's date is 60 days or 45 days from the Contract_End_Date__c. Below is my code but I am getting this error: Dependent class is invalid and needs recompilation: Class RenewCredit : Static method cannot be referenced from a non static context: void CreditRenewalNotification.NotifyRenewal()

 

Apex Class: 

public with sharing class CreditRenewalNotification
{
    
    public static void NotifyRenewal()
    {
        Messaging.SingleEmailMessage AlertOver = new Messaging.SingleEmailMessage(); //Alert when greater than or equal to 2500
        Messaging.SingleEmailMessage AlertUnder = new Messaging.SingleEmailMessage(); //Alert when less than 2500
        
        String[] toAdd1 = new String[] 
        {
            'test@test.com'
        };
        
        String[] toAdd2 =  new String[] 
        {
            'tes1@test.com'
            
        };
        
        Account[] acct = [SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL];
        
        for(Account a: acct)
        {
            String sURL = URL.getSalesforceBaseUrl().toExternalForm()+ '/'+a.Id;
            Date tod = System.today();
            System.debug('%%%%%%%%% '+tod);
            Date contEnd = a.Contract_End_Date__c;
            System.debug('&&&&& '+contEnd);
            Integer dayDiff = contEnd.daysBetween(tod);
            System.debug('******* '+dayDiff);
            
            
            if(dayDiff == 60)
            {    
                Integer days = 60;
                
            	if(a.Contract_Amount__c >= 2500)
                {
                    String bod = 'The following account will need to be renewed in '+days+'.<br/>';
                    bod += 'Name: '+a.Name+ '<br/>';
                    bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                    bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                    bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                    bod += 'Link: '+sURL+ '<br/>';
                    
                    AlertOver.setSubject('ALERT: '+a.Name+ 'has a contract expiring in '+days+' days.');
                    AlertOver.setToAddresses(toAdd1);
                    AlertOver.setSaveAsActivity(False);
                    AlertOver.setHtmlBody(bod);
                    
                    try {
                            Messaging.sendEmail(new Messaging.Email[] {
                                AlertOver
                            });
                        } catch (Exception e) {
                            System.debug('An unexpected error has occurred: ' + e.getMessage());
                        }
                
                }
                else
                {
                    
                    String bod = 'The following account will need to be renewed in '+days+'.<br/>';
                    bod += 'Name: '+a.Name+ '<br/>';
                    bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                    bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                    bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                    bod += 'Link: '+sURL+ '<br/>';
                    
                    AlertUnder.setSubject('ALERT: '+a.Name+ 'has a contract expiring in '+days+' days.');
                    AlertUnder.setToAddresses(toAdd2);
                    AlertUnder.setSaveAsActivity(False);
                    AlertUnder.setHtmlBody(bod);
                    
                    
                    try {
                            Messaging.sendEmail(new Messaging.Email[] {
                                AlertUnder
                            });
                        } catch (Exception e) {
                            System.debug('An unexpected error has occurred: ' + e.getMessage());
                        }
                    
                }
            }
            if(dayDiff == 45)
            {
                Integer days1 = 45;
                
                if(a.Contract_Amount__c >= 2500)
                {
                    try {
                            Messaging.sendEmail(new Messaging.Email[] {
                                AlertOver
                            });
                        } catch (Exception e) {
                            System.debug('An unexpected error has occurred: ' + e.getMessage());
                        }
                    
                }
                else
                {
                    try {
                            Messaging.sendEmail(new Messaging.Email[] {
                                AlertUnder
                            });
                        } catch (Exception e) {
                            System.debug('An unexpected error has occurred: ' + e.getMessage());
                        }
                    
                }    
            }
        }
    	
    }
}


Scheduler class:

global class RenewCredit implements Schedulable{
global void execute(SchedulableContext SC) {
        CreditRenewalNotification cred = new CreditRenewalNotification();
        cred.NotifyRenewal();
    }
}


Any help one this would be great! Thanks!
 
Best Answer chosen by ApexNewbie77
SHAHNA MULLASHAHNA MULLA
Hi,

Try below code for your scheduler class,
global class RenewCredit implements Schedulable{
global void execute(SchedulableContext SC) {
        CreditRenewalNotification.NotifyRenewal();
    }
}

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!

All Answers

SHAHNA MULLASHAHNA MULLA
Hi,

Try below code for your scheduler class,
global class RenewCredit implements Schedulable{
global void execute(SchedulableContext SC) {
        CreditRenewalNotification.NotifyRenewal();
    }
}

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!
This was selected as the best answer
ApexNewbie77ApexNewbie77

Hi Shanna,

Thank you for responding! That certainly helped!

 

However, I am not experiencing this issue: Too many Email Invocations: 11

I believe my issue is that I am hitting the governer limit of 10 emails but I cannot set my batch scope to 1 because it needs to be 200? Any help would be appreciated.

Below is my code:

Batch Class:

global class BatchRenewal implements Database.Batchable<sObject>{
    
    public String query = 'SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL';
    
    global Database.queryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator(query); // you can modify the query as per your requirement.
    }
    
    global void execute (Database.BatchableContext BC, List<Account> acct)
    {
            
            Messaging.SingleEmailMessage AlertOver = new Messaging.SingleEmailMessage(); //Alert when greater than or equal to 2500
            Messaging.SingleEmailMessage AlertUnder = new Messaging.SingleEmailMessage(); //Alert  when less than 2500
            
            String[] toAdd1 = new String[] 
            {
               test@test.com
            };
            
            String[] toAdd2 =  new String[] 
            {
                test1@test.com
            };
            
            //Account[] acct = [SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL];
            
            for(Account a: acct)
            {
                String sURL = URL.getSalesforceBaseUrl().toExternalForm()+ '/'+a.Id;
                Date tod = System.today();
                System.debug('%%%%%%%%% '+tod);
                Date contEnd = a.Contract_End_Date__c;
                System.debug('&&&&& '+contEnd);
                Integer dayDiff = contEnd.daysBetween(tod);
                System.debug('******* '+dayDiff);
                
                
                if(dayDiff == 60)
                {    
                    Integer days = 60;
                    
                    if(a.Contract_Amount__c >= 2500)
                    {
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertOver.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertOver.setToAddresses(toAdd1);
                        AlertOver.setSaveAsActivity(False);
                        AlertOver.setHtmlBody(bod);
                        
                        try {
                                Messaging.sendEmail(new Messaging.Email[] {
                                    AlertOver
                                });
                            } catch (Exception e) {
                                System.debug('An unexpected error has occurred: ' + e.getMessage());
                            }
                    
                    }
                    else
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertUnder.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertUnder.setToAddresses(toAdd2);
                        AlertUnder.setSaveAsActivity(False);
                        AlertUnder.setHtmlBody(bod);
                        
                        
                        try {
                                Messaging.sendEmail(new Messaging.Email[] {
                                    AlertUnder
                                });
                            } catch (Exception e) {
                                System.debug('An unexpected error has occurred: ' + e.getMessage());
                            }
                        
                    }
                }
                
                if(dayDiff == 30)
                {
                    Integer days = 30;
                    
                    if(a.Contract_Amount__c >= 2500)
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertOver.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertOver.setToAddresses(toAdd1);
                        AlertOver.setSaveAsActivity(False);
                        AlertOver.setHtmlBody(bod);
                        
                        try {
                                Messaging.sendEmail(new Messaging.Email[] {
                                    AlertOver
                                });
                            } catch (Exception e) {
                                System.debug('An unexpected error has occurred: ' + e.getMessage());
                            }
                        
                    }
                    else
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertUnder.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertUnder.setToAddresses(toAdd2);
                        AlertUnder.setSaveAsActivity(False);
                        AlertUnder.setHtmlBody(bod);
                        
                        try {
                                Messaging.sendEmail(new Messaging.Email[] {
                                    AlertUnder
                                });
                            } catch (Exception e) {
                                System.debug('An unexpected error has occurred: ' + e.getMessage());
                            }
                        
                    }    
                }
            }
            
        }
        
       
   
    
    global void finish(Database.BatchableContext BC){      
        
    }
}

Schedule Class:

global class ScheduleBatchRenewal implements Schedulable {
   global void execute(SchedulableContext sc) {
      BatchRenewal b = new BatchRenewal(); 
      database.executebatch(b, 1);
   }
}


Test Class:​

@isTest
private class BatchRenewalTest
{
    @testSetup
    static void setup() 
    {
        List<Account> acct = new List<Account>();
        for(Integer i=0;i<3;i++)
        {
            String nam = 'Apple'+i;
            Integer am = 250 + i;
            acct.add(new Account(Name=nam, Type='RAW',Sales_Team__c='B2B', Contract_End_Date__c=Date.newInstance(2018,6,10),Contract_Amount__c=am));
        }
        
        for(Integer i=0;i<3;i++)
        {
            String nam = 'Orange'+i;
            Integer am = 5000 + i;
            acct.add(new Account(Name=nam, Type='RAW',Sales_Team__c='B2B', Contract_End_Date__c=Date.newInstance(2018,6,10),Contract_Amount__c=am));
        }
        
        for(Integer i=0;i<3;i++)
        {
            String nam = 'Banana'+i;
            Integer am = 250 + i;
            acct.add(new Account(Name=nam, Type='RAW',Sales_Team__c='B2B', Contract_End_Date__c=Date.newInstance(2018,7,10),Contract_Amount__c=am));
        }
        for(Integer i=0;i<3;i++)
        {
            String nam = 'Grape'+i;
            Integer am = 5000 + i;
            acct.add(new Account(Name=nam, Type='RAW',Sales_Team__c='B2B', Contract_End_Date__c=Date.newInstance(2018,7,10),Contract_Amount__c=am));
        }
        
        insert acct;
        System.debug(Acct);
        
    }
    
    static testmethod void test() 
    { 
    	Test.startTest();
        BatchRenewal uca = new BatchRenewal();
        uca.query='SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL';
        Id batchId = Database.executeBatch(uca, 200);
        
        ScheduleBatchRenewal sch = new ScheduleBatchRenewal();
        sch.execute(null);
        
        Test.stopTest();
    }
}
SHAHNA MULLASHAHNA MULLA
Hi,

Please modify your batch class like this,
global class BatchRenewal implements Database.Batchable<sObject>{
    
    public String query = 'SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL';
    
    global Database.queryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator(query); // you can modify the query as per your requirement.
    }
    
    global void execute (Database.BatchableContext BC, List<Account> acct)
    {
            
            Messaging.SingleEmailMessage AlertOver = new Messaging.SingleEmailMessage(); //Alert when greater than or equal to 2500
            Messaging.SingleEmailMessage AlertUnder = new Messaging.SingleEmailMessage(); //Alert  when less than 2500
            //List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
         	Messaging.SingleEmailMessage[] emails = new List<Messaging.SingleEmailMessage>();
            
            String[] toAdd1 = new String[] 
            {
               'test@test.com'
            };
            
            String[] toAdd2 =  new String[] 
            {
               'test1@test.com'
            };
            
            //Account[] acct = [SELECT Id, Name, Contract_Start_Date__c, Contract_End_Date__c, Contract_Amount__c FROM Account WHERE Contract_End_Date__c != NULL AND Contract_Amount__c != NULL];
            
            for(Account a: acct)
            {
                String sURL = URL.getSalesforceBaseUrl().toExternalForm()+ '/'+a.Id;
                Date tod = System.today();
                System.debug('%%%%%%%%% '+tod);
                Date contEnd = a.Contract_End_Date__c;
                System.debug('&&&&& '+contEnd);
                Integer dayDiff = contEnd.daysBetween(tod);
                System.debug('******* '+dayDiff);
                
                
                if(dayDiff == 60)
                {    
                    Integer days = 60;
                    
                    if(a.Contract_Amount__c >= 2500)
                    {
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertOver.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertOver.setToAddresses(toAdd1);
                        AlertOver.setSaveAsActivity(False);
                        AlertOver.setHtmlBody(bod);
                        emails.add(AlertOver);
                    }
                    else
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertUnder.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertUnder.setToAddresses(toAdd2);
                        AlertUnder.setSaveAsActivity(False);
                        AlertUnder.setHtmlBody(bod);
                        emails.add(AlertUnder);    
                    }
                }
                
                if(dayDiff == 30)
                {
                    Integer days = 30;
                    
                    if(a.Contract_Amount__c >= 2500)
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertOver.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertOver.setToAddresses(toAdd1);
                        AlertOver.setSaveAsActivity(False);
                        AlertOver.setHtmlBody(bod);
                        emails.add(AlertOver);   
                    }
                    else
                    {
                        
                        String bod = 'The following account will need to be renewed in '+days+' days.<br/>';
                        bod += 'Name: '+a.Name+ '<br/>';
                        bod += 'Contract Start Date: '+a.Contract_Start_Date__c+ '<br/>';
                        bod += 'Contract End Date: '+a.Contract_End_Date__c+ '<br/>';
                        bod += 'Contract Amount: $'+a.Contract_Amount__c+ '<br/>';
                        bod += 'Link: '+sURL+ '<br/>';
                        
                        AlertUnder.setSubject('ALERT: '+a.Name+ ' has a contract expiring in '+days+' days.');
                        AlertUnder.setToAddresses(toAdd2);
                        AlertUnder.setSaveAsActivity(False);
                        AlertUnder.setHtmlBody(bod);
                        emails.add(AlertUnder); 
                    }    
                }
            }
        	try {
                  Messaging.sendEmail(emails);
               	} catch (Exception e) {
                        System.debug('An unexpected error has occurred: ' + e.getMessage());
                } 
        }
           
    global void finish(Database.BatchableContext BC){      
        
    }
}

Let me know if it helps.
Thanks.