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
Pubali BanerjeePubali Banerjee 

Getting too many send email invocation error even though i am sending email to one email address

Getting too many send email invocation error even though i am sending email to one email address. Objective of the below code is to show a list in form of table and send email of that list in form of excel to the email address entered. The below code worked fine till i used pagination after which "Too many email invocation" error occured.
Below are my codes.
Apex class:
//will show 1000 eror
public class PieController {
    
    public String result{get;set;}
    public String qString{get;set;}
    public list<TerritoryBkp__c> result1{get;set;}
    public list<TerritoryBkp__c> result2{get;set;}
   // public List<List<TerritoryBkp__c>> result3{get;set;}
   public Set<String> terrSet =new Set<String>();
   public Set<String> terrBkpSet = new Set<String>();
   public Set<String> missingSetData = new Set<String>();
   public Set<String> nameSet = new Set<String>();
   public String terr =null;
   public String terr_bkp=null;
   public String subString=null;
   public String s1=null;
public List<wrapper> lstwrapper {get; set;}
    public string Filetype{get;set;}
    public string header{get;set;}
   public boolean res{get;set;}
    public String finalstr{get;set;}
    public String message{get;set;}
    public integer i{get;set;}
    public integer countTerr{get;set;}
    public integer countMismatch{get;set;}
   public integer counter=0;
    public integer list_size=30;
    
    
public void PieController() //replace with T2
    {
     countTerr=0;   
     i=0;
    List<Territory2> terrList = [SELECT Id,MSD_CORE_Country_Code__c,MSD_CORE_ParentTerritory1Id__c,Name from Territory2];
    List<TerritoryBkp__c> terrBkpList = [SELECT Id,MSD_CORE_Country_Code__c,MSD_CORE_Parent_Territory__c,Name from TerritoryBkp__c];
    res=false;
    
  
    for( Territory2 t: terrList) //replace with T2
    {
    terr=t.Name+'@'+t.MSD_CORE_Country_Code__c+'@'+t.MSD_CORE_ParentTerritory1Id__c; 
    terrSet.add(terr);
    }
    system.debug('Territory1 set----'+terrSet);
    system.debug('Territory1 SIZEEE----'+terrSet.size());
    for( TerritoryBkp__c t1: terrBkpList)
    {
    terr_bkp=t1.Name+'@'+t1.MSD_CORE_Country_Code__c+'@'+t1.MSD_CORE_Parent_Territory__c;
    terrBkpSet.add(terr_bkp);
    }
    system.debug('TerritoryBkp set----'+terrBkpSet);
    system.debug('TerritoryBkp SIZEEE----'+terrBkpSet.size());
    If(terrSet.size()==terrBkpSet.size())
    {
    If(terrSet.equals(terrBkpSet))
    {
    result='Verified! Territory table contains all data.';
  system.debug('Result-->'+result);
    }
    else{
        excecute(); 
    }
    }
    
    else
    {
    excecute();
        system.debug('Res in line 60-->'+res);
    }
    
    }
    public void excecute()
    {    res=true;
     i=1;
     countTerr=[select count() from TerritoryBkp__c];
     system.debug('Res in line 66_executemethod-->'+res);
       Filetype = '';
    lstwrapper = new List<wrapper>();
    header = 'Id,Territory Name,ParentTerritory Id,Country Code';
    finalstr = header ;
      
    result='Oops!Few data missing from Territory2 table. Please find the list of missing rows.';
    for(String s:terrBkpSet)
    {  
               if(!terrSet.contains(s)) 
               {
                missingSetData.add(s);
            }
    
}
         Iterator<String> itr = missingSetData.iterator();
        while(itr.hasNext()){
            s1=itr.Next();
            integer iend = s1.indexOf('@');
            
            if (iend != -1) 
            {
                subString= s1.substring(0 , iend);
            
            }
            nameSet.add(subString);
        }  
        result1=[Select t.Id, t.Name, t.MSD_CORE_Parent_Territory__c,t.MSD_CORE_Country_Code__c from TerritoryBkp__c t where t.Name=:nameSet];
     countMismatch=result1.size();  
     result2=[Select t.Id, t.Name, t.MSD_CORE_Parent_Territory__c,t.MSD_CORE_Country_Code__c from TerritoryBkp__c t where t.Name=:nameSet limit :list_size offset:counter];
     for(TerritoryBkp__c lw:result1)    
    {
        wrapper w = new wrapper();
        w.TerrId= lw.Id;
        w.TerrName= lw.Name;
        w.TerrParentId=lw.MSD_CORE_Parent_Territory__c;
        w.TerrCountryCode=lw.MSD_CORE_Country_Code__c;
        lstwrapper.add(w);  
        string recordString = '"'+lw.id+'","'+lw.Name+'","'+lw.MSD_CORE_Parent_Territory__c+'","'+lw.MSD_CORE_Country_Code__c +'"\n';
        finalstr = finalstr +recordString;

    }
 // sendEmail();   
     
    }
    public List<PieWedgeData> getPieData() {
        List<PieWedgeData> data = new List<PieWedgeData>();
        data.add(new PieWedgeData('Before TM2.0', countTerr));
        data.add(new PieWedgeData('Mismatched after TM2.0', countMismatch));
       return data;
    }
    
 public void sendEmail()
 {
     try{
   Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalstr);
string csvname= 'MissingTerrData.csv';
csvAttc.setFileName(csvname);
csvAttc.setBody(csvBlob);
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
String[] toAddresses = new list<string> {qString};
//String toAddresses=qString;
String subject ='Territory Mismatch Data CSV';
String body='Hi,\n';
body+='Please find attached the list of mismatched or missing territories.\n';
body += '\n Thank You,' ;
email.setSubject(subject);
email.setToAddresses( toAddresses );
email.setPlainTextBody(body);
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
if(!(String.isBlank(qString)))
{
Messaging.SendEmail(new Messaging.SingleEmailMessage[] {email});                    
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
if(r[0].IsSuccess() == true){
 message = 'Email Sent!'; 
}
}  
     } catch(Exception e){
        
         message = 'Please enter Email Address';
     }
 }
    public PageReference Beginning() { //user clicked beginning
      counter = 0;
        excecute();
      return null;
   }

   public PageReference Previous() { //user clicked previous button
      counter -= list_size;
       excecute();
      return null;
   }

   public PageReference Next() { //user clicked next button
      counter += list_size;
        excecute();
      return null;
   }

   public PageReference End() { //user clicked end
      counter = countMismatch - math.mod(countMismatch, list_size);
        excecute();
      return null;
   }

   public Boolean getDisablePrevious() { 
      //this will disable the previous and beginning buttons
      if (counter>0) return false; else return true;
   }

   public Boolean getDisableNext() { //this will disable the next and end buttons
      if (counter + list_size < countMismatch) return false; else return true;
   }

   public Integer getTotal_size() {
      return countMismatch;
   }

   public Integer getPageNumber() {
      return counter/list_size + 1;
   }

   public Integer getTotalPages() {
      if (math.mod(countMismatch, list_size) > 0) {
         return countMismatch/list_size + 1;
      } else {
         return (countMismatch/list_size);
      }
   }
     
    public class wrapper{
        public string TerrId {get; set;}
        public string TerrName{get; set;}
        public string TerrParentId{get; set;}
        public string TerrCountryCode{get; set;}
      //  public string dateval{get; set;}
      
    }
      
  
    public class PieWedgeData {

        public String Name { get; set; }
        public Integer Data { get; set; }

        public PieWedgeData(String Name, Integer Data) {
            this.Name = Name;
            this.Data = Data;
        }
    
}
    
}

Visualforce Page: 
<apex:page controller="PieController" title="Territory Verification" sidebar="false" showHeader="false" readOnly="true">
<style>

    .activeTab {background-color: #236FBD; color:white; background-image:none;font-size: 14px}
    .inactiveTab { background-color: lightgrey; color:black; background-image:none;font-size: 14px}
    .headerRow .TableTitle {
    background-color: #236FBD !important;
    background-image: none !important;
    color: #black !important; 
    font-size:100% !important; 
   }
.changecss
{
background-image: none !important;
background-color:lightblue !important;
    color:blue !important;

}
    .buttonclass
    {
    color:white !important;
background:#00CC00 !important;
border-left: 0px  !important;
border-top: 0px  !important;
border-bottom: 0px  !important;
border-right: 0px  !important;
    }
#ct{

        text-align:center;

        font-size: 25px;
    }

    </style>
<apex:form style="border-style:solid;border-width:2px;
                      border-color:black;background-color:lightgrey" id="form1">
    
<div style="background-color:LightBlue;">
<div id="ct" >
<h1>Territory Verification</h1>
</div>
    <apex:commandButton styleClass="buttonclass" value="Back" oncomplete="doRedirect();"/>
    <script type="text/javascript">
                function doRedirect(){
                    window.history.back();
                }

            </script>
    </div>

    <apex:pageBlock id="pg">
        
<apex:tabPanel switchType="client" selectedTab="name1" id="dataTabPanel" tabClass="activeTab" inactiveTabClass="inactiveTab">
    <b><apex:tab label="Territory Verification" name="name1" id="tabOne">
        <div style="text-align:center;font-size: 12px;color:green;">
        <b><apex:outputLabel value="{!message}" rendered="true"></apex:outputLabel></b> <br/>
        </div>
        <b> <apex:outputLabel value="Click here to verify data"></apex:outputLabel></b>
        <b> <apex:commandButton styleClass="buttonclass" value="Verify data" action="{!PieController}" rendered="true"/> </b><br/><br/>
        <b><apex:outputLabel value="Enter Email address to send data in your inbox!"/></b><br/><br/>
        <apex:inputTextarea style="width: 300px; height: 40px;" id="email" value="{!qString}"/>    
        <b> <apex:commandButton styleClass="buttonclass" value="Send Email" action="{!sendEmail}" rendered="true"/> </b><br/>
        <br/>
    </apex:tab>
    </b>
   
    <!--<apex:tab label="Export missing data list,if any" name="name2" id="tabTwo">
    <apex:commandButton value="Click here to Export" action="{!missingData}" rendered="true" rerender="true"/>
       </apex:tab>-->
       </apex:tabPanel>
   <apex:outputPanel id="thepanel">
           
            <b><apex:outputLabel value="{!result}" style="color:{!IF(AND(i!=NULL,i>0),'red','green')};"></apex:outputLabel></b> <br/><br/>
            <apex:pageBlockTable id="s1" rowClasses="changecss" value="{!result2}" var="t" rendered="{!res}">
            
                <apex:column headerClass="TableTitle" value="{!t.Id}" />
                <apex:column headerClass="TableTitle" value="{!t.Name}"/>
                <apex:column headerClass="TableTitle" value="{!t.MSD_CORE_Country_Code__c}"/>
                <apex:column headerClass="TableTitle" value="{!t.MSD_CORE_Parent_Territory__c}"/>
                
                <apex:facet name="footer">Showing Page # {!pageNumber} of {!totalPages}</apex:facet>
                
       </apex:pageBlockTable>
        
              </apex:outputPanel>
     <!--   <div align="right">
             
        <apex:commandButton action="{!Beginning}" title="Beginning" value="<<" disabled="{!disablePrevious}"/>
        <apex:commandButton action="{!Previous}" title="Previous" value="<" disabled="{!disablePrevious}" />        
        <apex:commandButton action="{!Next}" title="Next" value=">" disabled="{!disableNext}"/>
        <apex:commandButton action="{!End}" title="End" value=">>" disabled="{!disableNext}"/> 
        </div>-->
   <!--      <div align="right">
             
        <apex:commandButton action="{!Beginning}" title="Beginning" value="<<" disabled="{!disablePrevious}" reRender="s1"/>
        <apex:commandButton action="{!Previous}" title="Previous" value="<" disabled="{!disablePrevious}" reRender="s1"/>        
        <apex:commandButton action="{!Next}" title="Next" value=">" disabled="{!disableNext}" reRender="s1"/>
        <apex:commandButton action="{!End}" title="End" value=">>" disabled="{!disableNext}" reRender="s1"/> 
        </div>-->
        <apex:outputPanel rendered="{!If(res = true, true, false)}">
            <div align="right">
             
        <apex:commandButton action="{!Beginning}" title="Beginning" value="<<" disabled="{!disablePrevious}"/>
        <apex:commandButton action="{!Previous}" title="Previous" value="<" disabled="{!disablePrevious}" />        
        <apex:commandButton action="{!Next}" title="Next" value=">" disabled="{!disableNext}"/>
        <apex:commandButton action="{!End}" title="End" value=">>" disabled="{!disableNext}"/> 
        </div>
            <div>
              <b><h>Chart View:</h></b>  
            </div>
            <div style="text-align:center;font-size: 12px;color:green;">
             
            <apex:chart height="350" width="450" data="{!pieData}">
        <apex:pieSeries dataField="Data" labelField="Name"/>
        <apex:legend position="right"/>
    </apex:chart>
                   
            </div>
        </apex:outputPanel>
         
        <apex:image style="margin-top:50px;margin-left:1000px;" url="https://apmsd--apswatt1--c.visualforce.com/resource/1597122238000/ETM_Tool_Logo" width="15%" height="15%"/><br/>
    </apex:pageBlock>
</apex:form>
</apex:page>
ShirishaShirisha (Salesforce Developers) 
Hi Pubali,

Greetings!

This error occurs,if the sendEmail() fires more than 10 times as there is limit on this method.So,you need to add the debug statement to check number of times the sendEmail() method has fired in one transaction.

Please refer the below article for the sample code for clear idea on this.

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

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri