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
Akash AAkash A 

Help me with this Asynchronous apex

public class AttendanceEmailBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
    public Database.QueryLocator start(Database.BatchableContext context) {
        // Calculate start date for querying attendance records
        Date startDate = Date.today().addDays(3);
        Date endDate = startDate.addDays(3);

/*
 // Calculate start date for querying attendance records
    Datetime startDate = Datetime.now().addMinutes(1);
    Datetime endDate = startDate.addMinutes(1);
*/
        String query = 'SELECT Id, Name, Employee__c, Employee__r.Manager__r.Email__c, Statuss__c, Date__c ' +
                       'FROM Attendance__c ' +
                       'WHERE (Statuss__c = \'Present\' OR Statuss__c = \'Less than 9.15\' OR Statuss__c = \'Status Unknown\' OR Statuss__c = \'Shortfall\') ' +
                       'AND Date__c >= :startDate AND Date__c <= :endDate';

        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext context, List<Attendance__c> scope) {
        List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();

        for (Attendance__c att : scope) {
            if (att.Employee__r != null && att.Employee__r.Manager__r != null && att.Employee__r.Manager__r.Email__c != null) {
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setToAddresses(new List<String>{att.Employee__r.Employee_Email__c});
                email.setCcAddresses(new List<String>{att.Employee__r.Manager__r.Email__c});
                email.setSubject('Attendance Status Notification');
                email.setPlainTextBody('Dear ' + att.Employee__r.Name + ',\n\n' +
                                       'Your attendance on ' + att.Date__c + ' has a status of "' + att.Statuss__c + '".\n\n' +
                                       'Please review your attendance record.\n\n' +
                                       'Sincerely,\nYour Company');
                emailsToSend.add(email);
            }
        }

        // Send the emails
        Messaging.SendEmailResult[] results = Messaging.sendEmail(emailsToSend);
        for (Messaging.SendEmailResult result : results) {
            if (result.isSuccess()) {
                System.debug('Email sent successfully.');
            } else {
                System.debug('Failed to send email. Error: ' + result.getErrors()[0].getMessage());
            }
        }
    }

    public void finish(Database.BatchableContext context) {
        // Perform any post-processing or cleanup if needed
    }
}

Used This one Batch class but it is not sending emails plz anone provide solution plz.

Full question Link:- https://developer.salesforce.com/forums/ForumsMain?id=9065d0000007BDKAA2
SwethaSwetha (Salesforce Developers) 
HI Akash,

> Have you checked the debug logs after running the batch to see if there are any error messages or unexpected behavior logged?

> Could you provide more details about the debug logs, particularly any log messages related to the email sending process?

> Are the Employee__r.Employee_Email__c and Employee__r.Manager__r.Email__c fields populated correctly with valid email addresses for the relevant records?

Thanks
Naresh Kaneriya 9Naresh Kaneriya 9
Hi Akash A,

The provided code seems to be correctly designed for sending emails based on attendance records, but there could be various reasons why the emails are not being sent. Here are a few troubleshooting steps and suggestions to help you identify and resolve the issue:

Check Email Deliverability:
Make sure that your Salesforce org's email deliverability settings are properly configured. If emails are blocked or not being delivered, it could be due to your organization's email settings.

Email Addresses:
Double-check that the relevant email addresses (Employee_Email__c and Manager__r.Email__c) are populated correctly on the related objects (Employee__r and Employee__r.Manager__r).

Scheduled Jobs: Check if there are any scheduled jobs that might be conflicting with or affecting the execution of the batch job.

Permissions: Ensure that the user executing the batch job has the necessary permissions to send emails and access the required objects and fields.

Please let me know if your problem is resolved. 
Thanks, Naresh

 
Akash AAkash A

Hi,

Thanks for the reply the below code tested using execute anonymous window code it is sending emails.

 

But how to schedule this and make it work as per actual requirement. Starting from 3rd day of month from there onwards every 3 days i want to schedule.

 

Plz help me with this.

Batch Class:-

public class AttendanceAuto implements Database.Batchable<SObject>, Database.AllowsCallouts, Schedulable {
    
     public void execute(SchedulableContext sc) {
        Datetime now = Datetime.now();
        Integer dayOfMonth = now.day();
        
        Datetime startDate = Datetime.newInstance(now.year(), now.month(), 3, 0, 0, 0);
        if (dayOfMonth > 3) {
            startDate = startDate.addDays(dayOfMonth - 3);
        }
        
        Datetime nextRunTime = startDate;
        while (nextRunTime <= now) {
          //  System.schedule('Attendance Batch Job', nextRunTime, this);
            
            nextRunTime = nextRunTime.addDays(3);
        }
    }

    public Database.QueryLocator start(Database.BatchableContext context) {
        Datetime batchStartDate = System.now().addDays(-3); 
        Datetime batchEndDate = System.now();
        
        return Database.getQueryLocator([
            SELECT Id, Name, Employee__c, Employee__r.Name, Employee__r.Email__c, Employee__r.Manager__r.Email__c, Statuss__c, Date__c, CreatedDate, Processed__c
            FROM Attendance__c 
            WHERE (Statuss__c = 'Shortfall' OR Statuss__c = 'Present' OR Statuss__c = 'Less than 9.15' OR Statuss__c = 'Status Unknown')
            AND CreatedDate >= :batchStartDate AND CreatedDate < :batchEndDate
            AND Processed__c = false
        ]);
    }
 public void execute(Database.BatchableContext context, List<Attendance__c> scope) {
        List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();

        for (Attendance__c att : scope) {
            try {
                if (att.Employee__r != null && att.Employee__r.Name != null && att.Employee__r.Email__c != null && att.Employee__r.Manager__r != null && att.Employee__r.Manager__r.Email__c != null) {
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    email.setToAddresses(new List<String>{att.Employee__r.Email__c});
                    email.setCcAddresses(new List<String>{att.Employee__r.Manager__r.Email__c});
                    email.setSubject('Attendance Status Notification');
                    
                    Datetime dateAndTime = DateTime.newInstance(att.Date__c.year(), att.Date__c.month(), att.Date__c.day());
                   // String formattedDateAndTime = dateAndTime.format('MMMM dd, yyyy h:mm a', 'UTC');
                   // + formattedDateAndTime
                    email.setPlainTextBody('Dear ' + att.Employee__r.Name + ',\n\n' +
                       'Your attendance on Submitted Date:- '+ att.Date__c +', Created Date:-' + att.createdDate +' has a status of "' + att.Statuss__c + '".\n\n' +
                       'Please review your attendance record.\n\n' +
                       'Record Link: https://-dev-ed.develop.lightning.force.com/lightning/r/Attendance__c/' + att.Id + '/view' +
                       '\n\nSincerely,\nSalesforce');

                    emailsToSend.add(email);
                    att.Processed__c = true;
                } else {
                    System.debug('Skipping record with Id: ' + att.Id + ' due to missing or invalid email addresses.');
                }
            } catch (Exception ex) {
                System.debug('Error processing record with Id: ' + att.Id + '. Error: ' + ex.getMessage());
            }
        }
        
        update scope;
        
        if (!emailsToSend.isEmpty()) {
            Messaging.SendEmailResult[] results = Messaging.sendEmail(emailsToSend);
            for (Messaging.SendEmailResult result : results) {
                if (result.isSuccess()) {
                    System.debug('Email sent successfully.');
                } else {
                    System.debug('Failed to send email. Error: ' + result.getErrors()[0].getMessage());
                }
            }
        } else {
            System.debug('No emails to send.');
        }
    }

    public void finish(Database.BatchableContext context) {
    }
}