Automatic email scheduler to Contacts accosiated with those Opportunities

Batch Class:

global class opptyDetails implements Database.Batchable<sobject>
{
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        String soql = 'SELECT Opportunity.Name, Opportunity.OrderNumber__c, Opportunity.Approval_Status__c, Contact.Email, Contact.Name, Contact.Level__c FROM OpportunityContactRole';
        return Database.getQueryLocator(soql);
    }
   
    global void execute(Database.BatchableContext bc, List<OpportunityContactRole> recs)
    {
        List<Messaging.SingleEmailMessage> msgs = new List<Messaging.SingleEmailMessage>();
        for(OpportunityContactRole ocr : recs)
        {
            Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
            msg.setSubject('Opportunity Detail');
            List<String> toAddresses = new List<String>();
            toAddresses.add(ocr.Contact.Email);
            msg.setToAddresses(toAddresses);
            msg.setHTMLBody('Hi ' + ocr.Contact.Name + ',<br/>Below is the Opportunity Detail.<br/>Opportunity Name: ' + ocr.Opportunity.Name + '<br/>Order Number: ' + ocr.Opportunity.OrderNumber__c + '<br/>Approval Status: ' + ocr.Opportunity.Approval_Status__c + '<br/><br/>Regards,<br/>Admin');
           
            msgs.add(msg);
        }
        if(!msgs.isEmpty())
        {
            messaging.sendEmail(msgs);
        }
    }
   
    global void finish(Database.BatchableContext bc)
    {
    }
}


Scheduler Class:

global class scheduleOpptyDetails implements schedulable
{
    global void execute(SchedulableContext sc)
    {
        opptyDetails od = new opptyDetails();
        Database.executeBatch(od);
    }
}




Apex Scheduler:





Output:



No comments:

Post a Comment