1

I have a legacy code in which it is sending email to a bulk of contacts. If the date range I'm selecting is more, I'm getting Too Many Email invocation error.

I have also attached the picture of error what I'm getting. enter image description here Here is the part of code triggering the error

  public void mailblock(string email,string repid,string CCEmail,string alterEmails,string GroupMail,string Choice,string RepName){

    System.debug('Mailblock function Entry:::::');
    lstEvent=[Select Description,id,StartDateTime,LeadID__c,ActivityDate , EndDateTime,SalesrepID__c,Assigned_Sales_rep__c  From Event where SalesrepID__c=:RepId and ActivityDate>=:Date.valueOf(ApexPages.currentPage().getParameters().get('fDate'))and ActivityDate<=:Date.valueOf(ApexPages.currentPage().getParameters().get('TDate')) ];
    List<Date> seDate = new List<Date>();
    DateTime FDate=DateTime.valueOf(ApexPages.currentPage().getParameters().get('fDate')+' 00:00:00');
    DateTime TDate=DateTime.valueOf(ApexPages.currentPage().getParameters().get('tDate')+' 00:00:00');
   if(FDate!=null && TDate!=null){
        seDate = gensedate(FDate,TDate);
   }
    System.Debug('MyDate'+seDate);
    Datetime myDT = Datetime.now();
    if(seDate.size()>0){
        for(Date d:seDate){
            string sending='0';
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setUseSignature(false);
            if(checkboxValue=='false')
                    {
                    Document doc = [select id, name, body, contenttype, developername, type from Document WHERE Name = 'Required Finance Documents Form'];
                    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
                    attach.setContentType(doc.contentType);
                    attach.setFileName(doc.developerName+'.'+doc.type);
                    attach.setInline(false);
                    attach.Body = doc.Body;
                    mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });
                    }
            mail.setToAddresses(new String[] { email });
            mail.setCCAddresses(new String[] { CCEmail });
            String[] BCCAddressList = new String[]{};
            string emails='';
            String[] BCCAddresses = new String[]{};
            if(alterEmails!='' && alterEmails!=null){
                BCCAddresses.add(alterEmails);
            }
            if(GroupMail!='' && GroupMail!=null){
                BCCAddresses.add(GroupMail);
            }
            if(BCCAddresses.size()>0){
                mail.setBCCAddresses( BCCAddresses );
            }
           // mail.setHtmlBody('http://premiercare.force.com/AppSheet?id='+RepId+'&fdate='+String.ValueOf(d).replace(' 00:00:00',''));
            // Send the email
            if(lstEvent.size()>0){
                system.debug('lstEvent values:::::::');
            for(Event E:lstEvent){
                if(E.SalesrepID__c==RepId && E.ActivityDate==Date.valueOf(d)){
                    System.Debug('RepName++'+RepName);
                    string CS=string.ValueOf(d)+' 00:00:00';

                    AppEmailMap__c objAppEmail= new AppEmailMap__c();
                    objAppEmail.SalesRepId__c=RepId;
                    objAppEmail.SalesRep__c=RepId;
                    objAppEmail.AppDate__c=Date.valueOf(d);
                    insert objAppEmail;
                    objAppEmail.Appt_Sheet_Link__c=URL.getSalesforceBaseUrl().toExternalForm()+'/apex/VFAppoinment?id='+RepId+'&fdate=' +String.ValueOf(d).replace(' 00:00:00','')+'&EId='+string.valueof(objAppEmail.Id);
                    update objAppEmail;

                    mail.setSubject(RepName+' check your Appoinment(s) on ' +  String.ValueOf(DateTime.ValueOf(CS).format('MM-dd-yyyy')).replace(' 00:00:00',''));
                    if(checkboxValue=='false')
                    {
                    Document doc = [select id, name, body, contenttype, developername, type from Document WHERE Name = 'Required Finance Documents Form'];
                    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
                    attach.setContentType(doc.contentType);
                    attach.setFileName(doc.developerName+'.'+doc.type);
                    attach.setInline(false);
                    attach.Body = doc.Body;
                    mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });
                    }
                    mail.setHtmlBody('Your AppointmentSheet:'+'To View Appointments <a href=http://premiercare.force.com/AppSheet?id='+RepId+'&fdate=' +String.ValueOf(d).replace(' 00:00:00','')+'&EId='+string.valueof(objAppEmail.Id)+'>click here</a><br/><br/><b><i><font size="2">Please keep in mind that appointment timesheet links are only accessible within 24 hours of the appointment date. Please check back if necessary (i.e. Holidays, etc.) as it is your responsibility to attend appointments on time regardless of when your timesheets are received.</font></i></b>');
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
                    sending='1';
                    break;
                }
            }
          }

          if(Choice=='1'){
               if(sending=='0'){
                   System.Debug('RepName++&'+RepName);
                   string CS=string.ValueOf(d)+' 00:00:00';
                    mail.setSubject(RepName+' Appoinment not Scheduled on ' +  String.ValueOf(DateTime.ValueOf(CS).format('MM-dd-yyyy')).replace(' 00:00:00',''));
                    if(checkboxValue=='false')
                    {
                    Document doc = [select id, name, body, contenttype, developername, type from Document WHERE Name = 'Required Finance Documents Form'];
                    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
                    attach.setContentType(doc.contentType);
                    attach.setFileName(doc.developerName+'.'+doc.type);
                    attach.setInline(false);
                    attach.Body = doc.Body;
                    mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });
                    }
                    mail.setHtmlBody('Appointment not available on'+ String.ValueOf(DateTime.ValueOf(CS).format('MM-dd-yyyy')).replace(' 00:00:00','') );
                    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
               }
           }else{
               sending='1';
           }
          }
    }else{
        system.debug('Else part Entry');
       send(email,repid,CCEmail,alterEmails);

    }
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with PDF sent to '+email + ' and '+ CCEmail ));

}
0

1 Answer 1

3

Why am I getting 'Too Many API email invocations 11' error message?

Resolution:

There is no 10 email limit from Apex. The limit is on the number of times the SendEmail() method can be invoked from Apex. We need to ensure that we are not calling SendEmail() method inside a for loop.

In a single transaction you can invoke singleEmail message send method only 10 times.

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 

If you just remove this line and add outside of your for loop(see below example)

then this method will invoke only once this way you can solve your issue


Updates

you code will be like this.

take a variable

List<Messaging.SingleEmailMessage> lstmail = new List<Messaging.SingleEmailMessage>();

//your for loop
for(//your code here)
{
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

  //rest of your code

  lstmail.add(mail );//add into list
}

Messaging.sendEmail(lstmail); //invoke here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .