Write a batch class to send an email to Opportunity owner. On 1st of each month send an email to Opportunity owner if close date is in this month. please give explnation after code thanks
public class BatchOnOpportunity implements DataBase.Batchable<sObject>{
public List<Opportunity> oppList{set;get;}
public List<String> emailList{set;get;}
public BatchOnOpportunity(){
oppList=[select id,OwnerId,Owner.Email,CloseDate from Opportunity where CloseDate=THIS_MONTH];
}
public List<Opportunity> start(DataBase.BatchableContext BC){
return oppList;
}
public void execute(Database.BatchableContext BC,List<Opportunity> opportunityList){
emailList=new List<String>();
for(Opportunity op:opportunityList){
emailList.add(op.Owner.Email);
}
system.debug('emailList::::'+emailList);
sendmail();
}
public void sendmail()
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setSubject(' Close Date Reminder');
email.setPlainTextBody('Your close date is belongs to this Month');
email.setToAddresses(emailList);
Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
}
public void finish(Database.BatchableContext BC){
system.debug('emailList finish::::'+emailList);
}
}
Schedule Class:
global class BatchScheduleOnOportunity implements Schedulable {
global void execute(SchedulableContext sc)
{
BatchOnOpportunity bObj = new BatchOnOpportunity();
database.executebatch(bObj);
}
}
You can take reference for scheduling class from the below link:
Hi Nilesh,
If above information helps then please mark it as Best Answer so that it can help others in the future.This is just a pseudocode do make the required correction as you may seem fit
Regards,
Priya Ranjan
Hi Nilesh,
Please find the solution.
Batch Class:
Schedule Class:You can take reference for scheduling class from the below link:
http://amitsalesforce.blogspot.com/2016/02/batch-apex-in-salesforce-test-class-for.html
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
Please let me know you are abale to schedule or not.
Please mark it as Best Answer
Thank You