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
Shruti NigamShruti Nigam 

send email after 7 days

Hi all,

I need to send email to the record owner after every 7 days which contains data of last six days.

Thanks in advance
Harsh P.Harsh P.
Hi Shruti,

This is the batch class to send email after the 7 Days of creation:
To schedule you need to create schedule apex and call this batch class into that schedule apex.
Then using Schedule apex button on apex class schedule it daily.
Batch class:
global class EmailAfter7DaysBatch implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query = 'Select Id,LastName,Owner.Email,OwnerId,CreatedDate,Email from Contact where Email != null AND Owner.Email != null';
        system.debug(query);
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {     
        try{
        system.debug(scope);
        EmailTemplate emailTemplate = [select Id, Body from EmailTemplate where DeveloperName = 'Email_To_Owner_After_7_Days'];
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
        Date d =System.Today();
        system.debug(d);
        
        for(Contact con : scope) {
                date convCD =con.CreatedDate.date();
                date after7Day = convCD.addDays(7);
                system.debug(convCD);
                system.debug(after7Day);
                boolean cmpdt = d.isSameDay(after7Day);
                system.debug('Email>>'+ con.Email);
                system.debug('OwnerEmail>>'+ con.Owner.Email);
            
                if( cmpdt == true ){
                system.debug(cmpdt);
                String[] toAddresses = new String[] {con.Email,con.Owner.Email};
                email.setToAddresses(toAddresses);
                email.setSaveAsActivity(false);
                email.setTargetObjectId(con.OwnerId);
                email.setTemplateId(emailTemplate.Id);
                email.setTreatTargetObjectAsRecipient(true); 
                system.debug(email);
                }else{
                    system.debug('Condition is false');
                }
        }
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        }catch(exception e){
            system.debug('Exception>>>'+ e.getMessage());
        }
    }

    global void finish(Database.BatchableContext BC)
    {
    }
}

If this solution find the help then mark as Best Answere.
Thanks...!