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
Shubham Sinha 56Shubham Sinha 56 

How to send email alert using batch class

Hello Everyone,

I have a requirement where I need to send an email alert to the owner of the lead if a Lead has been in 'New' Status for 48 hours i.e. after 48 hours owner should get an email if the status remains 'New' for 48 hours  and also if the same lead has been in "Working" status for 5 days ,after 5 days also i need to send an email alert to the owner of the lead.
Can i perform both the action from a single batch. If yes then how can I query for both the condition.Please help me on this.
ANUTEJANUTEJ (Salesforce Developers) 
Hi Shubham,

>> https://developer.salesforce.com/forums/?id=9062I000000IGMgQAO#:~:text=%2F%2FSend%20an%20email%20to,SingleEmailMessage()%3B

The above link has an implementation of sending an email with a batch class, you can try checking this once:

For the query you can try checking this Soql and modifying to fit the API names in your org:
 
SELECT Id FROM Lead WHERE (CreatedDate >= LAST_N_DAYS:2 AND Status = 'NEW') OR (LastModifiedDate >= LAST_N_DAYS:5 AND Status = 'Working')

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
Suraj Tripathi 47Suraj Tripathi 47
Hi Shubham,
Greetings!

1. First of all, you have to create a custom field in Lead.
Data Type - Date
Field Label - statusChangeDate
Field Name - statusChangeDate
Default Value - TODAY()

2. Create a Process builder,
Process Name - Lead Status Change
API Name - Lead_Status_Change
The process starts when - A record changes
Click on save.

3. Creating Process builder
    a. Add Object
    -> Object - Lead
    -> Start the process - when a record is created or edited
    -> Save

    b.Add Criteria
    -> Criteria Name - IsStatusChanged
    -> Criteria for Executing Actions - Conditions are met
    -> Set Conditions
        Field - Status
        Operator - Is changed
        Type - Boolean
        Value - True
        Conditions - All of the conditions are met (AND)
        Save
    -> MMEDIATE ACTIONS -> Add Action
        Action Type - Update Records
    Action Name - updateStatusChangeDate
    Record Type - Select the Lead record that started your process
    Criteria for Updating Records - No criteria—just update the records!
    -> Set new field values for the records you update
        Field - statusChangeDate
        Type - Formula
        Value - TODAY() 
    Save

4. Activate the process builder by click on Activate.

5. Create a Apex Batchable and Schedulable class that runs daily sends mail to the owner.
public class LeadOwnerAlert implements Database.Batchable<sObject>,Schedulable {
    public Database.QueryLocator start(Database.BatchableContext BC){
        Date checkDate1 = Date.today()-2;
        Date checkDate2 = Date.today()-5;
        return Database.getQueryLocator([SELECT Name, Status, Owner.Email, statusChangeDate__c FROM Lead WHERE (Status = 'New' OR Status = 'Working') AND (statusChangeDate__c = :checkDate1 OR statusChangeDate__c = :checkDate2)]);
    }
    public void execute(Database.BatchableContext BC, List<Lead> leadList){
        Messaging.SingleEmailMessage[] emailList = new List<Messaging.SingleEmailMessage>();
        Date checkDate1 = Date.today()-2;
        Date checkDate2 = Date.today()-5;
        for(Lead ldObj : leadList){
            if((ldObj.Status == 'New' && ldObj.statusChangeDate__c == checkDate1) || (ldObj.Status == 'Working' && ldObj.statusChangeDate__c == checkDate2)) {
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setSubject('Lead status not changed');
                String daysDifference;
                if(ldObj.statusChangeDate__c == checkDate1) {
                    daysDifference = '2';
                }
                else {
                    daysDifference = '5';
                }
                email.setHtmlBody('Your lead name is '+ldObj.Name+' and status is '+ldObj.Status+' which is not changed from '+daysDifference+' Days.');
                List<String> emailTo = new List<String>();
                emailto.add(ldObj.Owner.Email);
                email.setToAddresses(emailTo);
                emailList.add(email);
            }
        }
        if(!emailList.isEmpty()) {
            Messaging.sendEmail(emailList, false);
        }
    }
    public void finish(Database.BatchableContext BC){
    }
    public void execute(SchedulableContext SC) {
        Database.executeBatch(new LeadOwnerAlert());
    }
}

6. Schedule this batch using Cron expression.
example for a daily morning at 8.
System.schedule('Lead Status Not Changed','0 0 8 1/1 * ? *', new LeadOwnerAlert());
If this helped you please mark it as the best answer.
Thank you!
Regards 
Suraj Tripathi.