I'm trying to send email to list of users using batch class, but its throwing below error for few records.
Error:
System.EmailException: SendEmail failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, List has more than 1 row for assignment to SObject: []
Please find my code below, for testing purpose i have hard coded my email address
Batch Class:
global class CustomObjectBatch implements Database.Batchable<sObject>,Database.Stateful {
global Integer recordsProcessed = 0;
global database.querylocator start(Database.BatchableContext BC)
{
String ExcludeList = Label.ExcludeRecords;
string Query = 'Select Id,Process_Name__c,Emails__c,Template_Name__c,From_Email__c FROM Custom_Object__c WHERE is_active__c = true';
return Database.getQueryLocator(Query);
}
global void execute(Database.BatchableContext BC, List<Custom_Object__c> scope)
{
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for(Custom_Object__c DQ:scope){
String orgWideEmail = DQ.From_Email__c;
List<String> emails=new List<String>();
if(DQ.Emails__c != null && DQ.Emails__c != '')
//emails = DQ.Emails__c.split(';');
emails.add('Testchandra@gmail.com');
EmailTemplate template = [SELECT id,HtmlValue FROM EmailTemplate WHERE DeveloperName = :DQ.Template_Name__c LIMIT 1];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(emails);
//Setting Org Wide Email
if(orgWideEmail != null && orgWideEmail != ''){
OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = :orgWideEmail limit 1];
if ( owea.size() > 0 ) {
mail.setOrgWideEmailAddressId(owea.get(0).Id);
}
}else{
mail.setSenderDisplayName('');
}
mail.setBccSender(false);
mail.setUseSignature(false);
mail.setTargetObjectId(userinfo.getuseriD());
mail.setTreatTargetObjectAsRecipient(false);
mail.setTemplateId(template.Id);
mail.SaveAsActivity = false;
mails.add(mail);
}
system.debug(mails.size()+'size####Value'+mails);
if(!Test.isRunningTest() && !mails.isempty()){
try{
Messaging.sendEmail(mails);
}catch(System.EmailException ex){
system.debug('getMessage #####'+ex.getMessage());
}
}
}
global void finish(Database.BatchableContext BC) {
}
}
Executing with below code:
CustomObjectBatch COB= new CustomObjectBatch ();
string Jobid= Database.executeBatch(COB, 1);
List<EmailTemplate>
. Though you're running batch with size of 1, it is not recommended to write SOQL in for loop. I can see there are two such SOQL in a single for loop. – Rohit Mourya Jan 7 '20 at 7:26