I am writing a batch class to send the emails based on certian criteria. I see that the parameters are passed right, no errors, but I end up receiving multiple duplicate emails when I run it. Here is the code
Two issues that I am trying to resolve
When there are less than 10 emails to be sent out, the code works fine, but sends duplicate emails
When there are more than more than 10 emails in the list that I am sending to, I get an error saying:
FATAL_ERROR|System.LimitException: Too many Email Invocations: 11
Batch:
global void execute(Database.BatchableContext BC, List<OrderApi__Badge__c> scope){
for(Order_c fbdge : [select Id,Description__c,Type__c,Contact__c,Contact__r.Date__c,Contact__r.FirstName,Contact__r.Email,Active__c,Type__r.Name From Order__c where (Type__r.Name ='A' or Type__r.Name ='B') and OrderApi__Is_Active__c =true and (Contact__r.Cat__c <> ' Life')]){
bge.add(fbdge);
contact.put(fbdge.Contact__c, fbdge.Contact__r.Email);
}
if(contact.size()>0){
List<Messaging.SingleEmailMessage> mails = newList<Messaging.SingleEmailMessage>();
List<String> email = new List<String>();
List<String> ccemail = new List<String>();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
for(Id ids : contact.keyset()){
email.clear();
for(Order__c bdg :[select id,Contact__r.Email from Order__c where Contact__r.Email=:contact.get(ids) LIMIT 1]){
email.add(bdg.Contact__r.Email);
}
Contact c = [select id, Email from Contact where email <> null limit 1];
EmailTemplate templateId = [Select id from EmailTemplate where name = 'Test'];
mail.setToAddresses(email);
mail.setccAddresses(ccemail);
mail.setTargetObjectId(c.Id); mail.setTreatTargetObjectAsRecipient(false);
mail.setTemplateID(templateId.Id);
mail.setSaveAsActivity(false);
mails.add(mail);
if(mails.size())>0{
Messaging.sendEmail(mails);
}
}
}
}
global void finish(Database.BatchableContext BC){
}
}