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
SV MSV M 

Update Lead fields after email has been sent

Hi, I have a requirement where I am sending emails to Lead Email (Field in Lead) using a batch class. After sending the email I want to update the checkbox value to TRUE if the email is sent and FALSE if the email is not sent..
I've written the batch class but I am not sure how to update the field after email... Can someone help me with how to achieve this...
global class SendEmailToLeadBatch implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, Name, Email, Age_of_Lead__c, Email_Sent__c FROM Lead WHERE Age_of_Lead__c > 7 AND LeadSource = \'Partner Referral\'';
        return database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Lead> scope) {
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        for(Lead ldEmail : scope) {
            String body = 'The Lead '+ldEmail.Name+' age is '+ldEmail.Age_of_Lead__c+' Days';
            //String body = 'Hello '+ldEmail.Name+' is created '+ldEmail.Age_of_Lead__c+' Days;
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
            sendTo.add(ldEmail.Email);
            mail.setToAddresses(sendTo);
            mail.setSaveAsActivity(false);
            mail.setSubject('Hello '+ldEmail.Name+'');
            mail.setHtmlBody(body);
            emails.add(mail);
        }
        Messaging.SendEmailResult[] result = Messaging.sendEmail(emails);
        if(result[0].success) {
            
        }
    }
    global void finish(Database.BatchableContext BC) {
        
    }
}



 
ShirishaShirisha (Salesforce Developers) 

Hi Sai,

Greetings!

Unfortunately,sending an email is not a "triggerable" action.So,it is not possible to update the checkbox based on the Email status as mentioned here (https://salesforce.stackexchange.com/questions/205275/trigger-a-field-update-after-email-is-sent).

However,you can find the Sample code to update the Checkbox on daily basis using batch in the below link:

https://developer.salesforce.com/forums/?id=906F0000000kAqEIAU

Please mark it as best answer if it helps you to fix the issue.

Thank you!

Regards,
Shirisha Pathuri

SV MSV M
Hi, I was able to achieve the functionality using Database.Stateful interface. I have added all the Id's into a List and in the finish method updated the checkbox value...