function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shruti NigamShruti Nigam 

First error: Too many Email Invocations: 11

Hi all,
I have created a batch class but still i am getting error "First error: Too many Email Invocations: 11" .

Can anyone solve this issue.
Below is my batch class.
global class batchexpense implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        
       String query = 'Select Name_of_Employee__c from Expense_Management__c where CreatedDate = LAST_N_DAYS:15';
       return Database.getQueryLocator(query);
     }
    
	global void execute(Database.BatchableContext BC, List<Expense_Management__c> scope){
   		Set<String> myset = new Set<String>();
		for(Expense_Management__c aa : scope)
		{
  			myset.add(aa.Name_of_Employee__c);  
		}    
				
		
   		 for(Expense_Management__c cc : [select id,Name_of_Employee__r.email,Name_of_Employee__c from Expense_Management__c WHERE Name_of_Employee__c =: myset ])
        {
         
            list<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();  
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
			Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            PageReference pref = page.ExpenseReport;
            pref.getParameters().put('Id',cc.Name_of_Employee__c );
            pref.setRedirect(true);
             Blob b;
             if(Test.isRunningTest()) { 
                b = blob.valueOf('Unit.Test');
            } else {
                b = pref.getContent();
            }
            attach.setFileName('Expense.pdf');
            attach.setBody(b);
            semail.setSubject('Expense details');
            semail.setSaveAsActivity(true);
         
            semail.setReplyTo('noreply@gmail.com');
            semail.setSenderDisplayName('salesforce User');
            semail.setWhatId(cc.Id);
     
            
            List<String> sendTo = new List<String>();//to string
           	sendTo.add(cc.Name_of_Employee__r.email);
            semail.setToAddresses(sendTo);
           
            mails.add(semail);
            String emailBody =' <html><body><p> Dear  ,<br><br> Please find the attached Expense details. <br><br>    Regards, <br> IT Team <br>  Sayaji Groups.</p></body></html>';
            semail.setHtmlBody(emailBody);
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
        }
     }
    
    	global void finish(Database.BatchableContext BC){
        
    	}
}

Thanks in advance
Khan AnasKhan Anas (Salesforce Developers) 
Hi Shruti,

Greetings to you!

There is no email limit from Apex. The limit is on the number of times the sendEmail() method can be invoked from Apex. You need to ensure that you're not calling the sendEmail() method inside a for loop. You are getting this error because you are calling sendEmail() method inside for loop.
 
global class batchexpense implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        
       String query = 'Select Name_of_Employee__c from Expense_Management__c where CreatedDate = LAST_N_DAYS:15';
       return Database.getQueryLocator(query);
     }
    
	global void execute(Database.BatchableContext BC, List<Expense_Management__c> scope){
   		Set<String> myset = new Set<String>();
		for(Expense_Management__c aa : scope)
		{
  			myset.add(aa.Name_of_Employee__c);  
		}    
				
		Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
   		 for(Expense_Management__c cc : [select id,Name_of_Employee__r.email,Name_of_Employee__c from Expense_Management__c WHERE Name_of_Employee__c =: myset ])
        {
         
            list<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();  
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            PageReference pref = page.ExpenseReport;
            pref.getParameters().put('Id',cc.Name_of_Employee__c );
            pref.setRedirect(true);
             Blob b;
             if(Test.isRunningTest()) { 
                b = blob.valueOf('Unit.Test');
            } else {
                b = pref.getContent();
            }
            attach.setFileName('Expense.pdf');
            attach.setBody(b);
            semail.setSubject('Expense details');
            semail.setSaveAsActivity(true);
         
            semail.setReplyTo('noreply@gmail.com');
            semail.setSenderDisplayName('salesforce User');
            semail.setWhatId(cc.Id);
     
            
            List<String> sendTo = new List<String>();//to string
           	sendTo.add(cc.Name_of_Employee__r.email);
            semail.setToAddresses(sendTo);
           
            mails.add(semail);
            String emailBody =' <html><body><p> Dear  ,<br><br> Please find the attached Expense details. <br><br>    Regards, <br> IT Team <br>  Sayaji Groups.</p></body></html>';
            semail.setHtmlBody(emailBody);
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            
        }
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
     }
    
    	global void finish(Database.BatchableContext BC){
        
    	}
}

Please refer to the below links which might help you further.

https://help.salesforce.com/articleView?id=000324660&type=1&mode=1 (https://help.salesforce.com/articleView?id=000324660&type=1&mode=1)

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Deepali KulshresthaDeepali Kulshrestha
Hi Shruti,

Greetings to you!

Every time you invoke an email in the batch.The limit is on the number of times the sendEmail() method is 10.
If you hit 10 you must stop emailing from within the batch. Apex batch jobs are only allowed to send 10 emails max.
And also you need to ensure that you're not calling the sendEmail() method inside a for loop.

Please use below link.
https://help.salesforce.com/articleView?id=000324660&type=1&mode=1

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.
Ajay K DubediAjay K Dubedi
Hi Shruti,

I have gone through your code. I found you have written send email code inside the for_loop and your loop is iterate more the 10 times. That's why you get an error.   


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi