You need to sign in to do that
Don't have an account?

hii everyone!! I need to send email using email template when business days=5 in scheduler or batch apex. help me!!
global class BatchApex implements Database.Batchable<sObject>{ String query = 'SELECT Id,CLOSED__c, Priority FROM Case'; global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Case> cas){ for(Case c : cas){ if(c.priority=='High'){ c.CLOSED__c = TRUE; } } update cas; for(Case cs:cas){ if(cs.Business_days__c==5){ cas.add(cs); sendmail(); } } update cas; } global void finish(Database.BatchableContext BC){ } public void sendmail() { Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {'iswarya.sekar@excelenciaconsulting.com'} ; email.setToAddresses(toAddresses) ; email.setPlainTextBody('this is a test mail'); email.setSubject('New Case Logged'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email }); } }Its updating CLOSED__c to True, But it is not sending email when Business_days__c==5
Please write your logic of sending email in Finish method: I Hope this will work.
Regards,
Ramakant
Regards,
Ramakant
1. You need to add Business_days__c in your query before you use it in your code.
2. You are iterating over cas. Again you are updating the same. It will throw an error. Please create another list and add c to it and update the list. In the if condition of Business days you are only calling a method and not chnaging anything. So you need not update cases after that.
In short your code must be something like this :-
global class BatchApex implements Database.Batchable<sObject>{
String query = 'SELECT Id,CLOSED__c, Priority,Business_days__c FROM Case';
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Case> cas){
list<Case> lstUpdate = new list<Case>();
for(Case c : cas){
if(c.priority=='High'){
c.CLOSED__c = TRUE;
}
lstUpdate.add(c);
}
update lstUpdate;
for(Case cs:cas){
if(cs.Business_days__c==5){
//cas.add(cs);
sendmail();
}
}
//update cas;
}
global void finish(Database.BatchableContext BC){
}
public void sendmail()
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'test@gmail.com'} ;
email.setToAddresses(toAddresses) ;
email.setPlainTextBody('this is a test mail');
email.setSubject('New Case Logged');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
}
}
Also as a best practice it is good if you have the code of sending email in your finsih method.