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
Michael HaaseMichael Haase 

System.LimitException: Too many Email Invocations: 11

Dear colleagues,

could you please help? I am new to Apex and just struggeling with the "System.LimitException: Too many Email Invocations: 11" error.

I am trying to send an email to the Contact owner upon creation of a task for the contact. That works so far fine, except that I am breaking the governor limt for the number of emails to be sent.

This is my trigger:

trigger Individual_SM_Notification_v2 on Task (after insert) {

//Query for Contact    
//Step 1: Create a Set of all Contacts to query
Set<String> allWhoIds = new Set<String>();
for (Task newTask : Trigger.new){
if (newTask.WhoId != null){
allWhoIds.add(newTask.WhoId);
    system.debug('Step 1: ' + newTask.WhoId);
}
}

//Step 2:Query the Contact Ids from the WhoIds (from Step 1)
List <Contact> potentialContacts = [Select Id, Name, Owner.Email, Owner.LastName From Contact Where Id In :allWhoIds];
system.debug('List<Contact> Details: ' + potentialContacts);
   
    
    
//Step 3: Create Map to search Contacts by WhoId
Map<String, String>WhoIdToContactMap = new map<String, String>();
for (Contact c : potentialContacts){
WhoIdToContactMap.put(c.Id, c.Owner.Email);
}

// Create a master list to hold the emails we'll send
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
//Get the matching Contact Owner by the Contact Id
for (task newTask : Trigger.new){
String UserToUpdate = WhoIdToContactMap.get(newTask.WhoId);
System.debug('User to update: ' + UserToUpdate);
      

    
    
    
    
// Step 1: Create a new Email
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();    
    
// Step 2: Set list of people who should get the email
      List<String> sendTo = new List<String>();
      sendTo.add(UserToUpdate);
      mail.setToAddresses(sendTo); 
    System.debug('Step 2:' + sendTo);
    
    
// Step 3: Set who the email is sent from
      mail.setReplyTo('SalesforceAdmin@bcsprime.com');
      mail.setSenderDisplayName('BCS GMIB Research Team'); 
    system.debug('Step 3:' + mail);

// (Optional) Set list of people who should be CC'ed
      List<String> ccTo = new List<String>();
      ccTo.add('mhaase@bcsprime.com');
      mail.setCcAddresses(ccTo);    
    
 
// Step 4. Set email contents - you can use variables!
mail.setSubject('Research Call Update');
String body = 'Date: ' + newTask.ActivityDate + '<br/>';
body += 'Caller: ' + newTask.Assigned_To_Dupe__c + '<br/>';
body += 'Company Name: ' + newTask.Account_Name_dupe__c + '<br/>';
body += 'Contact Name: ' + newTask.Client_Name__c  + '<br/>';
body += 'Description: ' + newTask.Description + '<br/>';
mail.setHtmlBody(body);

// Step 5. Add your email to the master list
mails.add(mail);    


// Step 6: Send all emails in the master list
Messaging.sendEmail(mails);
          
}
}




This is my test class:

@isTest
public class TestLastResearchActivity_v2 {
    static testMethod void testLastResearchActivity_v2(){
        
        
        Account acc = new Account();
        acc.Name = 'ABC Investments';
        acc.RecordTypeId = '012b0000000UQ0L';
        insert acc;
        
        Account acctId = [Select Id From Account Where Name = 'ABC Investments'];
        
        
        Contact c = new Contact();
        c.LastName = 'Meier';
        c.RecordTypeId = '012b0000000USN6';
        insert c;
        
        //Lookup Contact Id
        Contact taskContact = [Select ID From Contact Where LastName = 'Meier'];
        
        
        //Create a list for the tasks to be updated
        List<Task> taskList = new List<Task>();
        
        //Tasks Chuyko
        Task t = new Task();
        t.WhatId = acctId.Id;
        t.RecordTypeId = '012b0000000URMt';
        t.OwnerId = '005b0000001R6YS';
        t.Communication_Type__c = 'Conversation';
        t.Whoid = taskContact.Id;
        insert t;
        
        
        //Tasks Petropavlovski
        Task t2 = new Task();
        t2.WhatId = acctId.Id;
        t2.RecordTypeId = '012b0000000URMt';
        t2.OwnerId = '005b0000001TATI';
        t2.Communication_Type__c = 'Conversation';
        t2.Whoid = taskContact.Id;
        insert t2;
        
        //Tasks Tikhomirov
        Task t3 = new Task();
        t3.WhatId = acctId.Id;
        t3.RecordTypeId = '012b0000000URMt';
        t3.OwnerId = '005b0000001TAgR';
        t3.Communication_Type__c = 'Conversation';
        t3.Whoid = taskContact.Id;
        insert t3;
        
        //Tasks Ibragimov
        Task t4 = new Task();
        t4.WhatId = acctId.Id;
        t4.RecordTypeId = '012b0000000URMt';
        t4.OwnerId = '005b0000001RKOq';
        t4.Communication_Type__c = 'Conversation';
        t4.Whoid = taskContact.Id;
        insert t4;
        
        //Tasks Naydennova
        Task t5 = new Task();
        t5.WhatId = acctId.Id;
        t5.RecordTypeId = '012b0000000URMt';
        t5.OwnerId = '005b0000001RKOl';
        t5.Communication_Type__c = 'Conversation';
        t5.Whoid = taskContact.Id;
        insert t5;
        
        //Tasks Goncharov
        Task t6 = new Task();
        t6.WhatId = acctId.Id;
        t6.RecordTypeId = '012b0000000URMt';
        t6.OwnerId = '005b0000001RKOg';
        t6.Communication_Type__c = 'Conversation';
        t6.Whoid = taskContact.Id;
        insert t6;
        
        //Tasks Tachennikov
        Task t7 = new Task();
        t7.WhatId = acctId.Id;
        t7.RecordTypeId = '012b0000000URMt';
        t7.OwnerId = '005b0000001TAUk';
        t7.Communication_Type__c = 'Conversation';
        t7.Whoid = taskContact.Id;
        insert t7;
        
        //Tasks Mitchell
        Task t8 = new Task();
        t8.WhatId = acctId.Id;
        t8.RecordTypeId = '012b0000000URMt';
        t8.OwnerId = '005b0000001RKOv';
        t8.Communication_Type__c = 'Conversation';
        t8.Whoid = taskContact.Id;
        insert t8;
        
        //Tasks Kotok
        Task t9 = new Task();
        t9.WhatId = acctId.Id;
        t9.RecordTypeId = '012b0000000URMt';
        t9.OwnerId = '005b0000001TAb7';
        t9.Communication_Type__c = 'Conversation';
        t9.Whoid = taskContact.Id;
        insert t9;
        }
}

Thanks in advance for your help!!!
Best Answer chosen by Michael Haase
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi Michael Haase,

Use below code to avoid calling 'sendEmail' method more than 10 times with in for loop.
Please keep 'SendEmail()' outside of for loop,as there is a limit of 10 invocations per execution context.
 
trigger Individual_SM_Notification_v2 on Task (after insert) {

//Query for Contact    
//Step 1: Create a Set of all Contacts to query
Set<String> allWhoIds = new Set<String>();
for (Task newTask : Trigger.new){
if (newTask.WhoId != null){
allWhoIds.add(newTask.WhoId);
    system.debug('Step 1: ' + newTask.WhoId);
}
}

//Step 2:Query the Contact Ids from the WhoIds (from Step 1)
List <Contact> potentialContacts = [Select Id, Name, Owner.Email, Owner.LastName From Contact Where Id In :allWhoIds];
system.debug('List<Contact> Details: ' + potentialContacts);
   
    
    
//Step 3: Create Map to search Contacts by WhoId
Map<String, String>WhoIdToContactMap = new map<String, String>();
for (Contact c : potentialContacts){
WhoIdToContactMap.put(c.Id, c.Owner.Email);
}

// Create a master list to hold the emails we'll send
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
//Get the matching Contact Owner by the Contact Id
for (task newTask : Trigger.new){
String UserToUpdate = WhoIdToContactMap.get(newTask.WhoId);
System.debug('User to update: ' + UserToUpdate);
      

    
    
    
    
// Step 1: Create a new Email
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();    
    
// Step 2: Set list of people who should get the email
      List<String> sendTo = new List<String>();
      sendTo.add(UserToUpdate);
      mail.setToAddresses(sendTo); 
    System.debug('Step 2:' + sendTo);
    
    
// Step 3: Set who the email is sent from
      mail.setReplyTo('SalesforceAdmin@bcsprime.com');
      mail.setSenderDisplayName('BCS GMIB Research Team'); 
    system.debug('Step 3:' + mail);

// (Optional) Set list of people who should be CC'ed
      List<String> ccTo = new List<String>();
      ccTo.add('mhaase@bcsprime.com');
      mail.setCcAddresses(ccTo);    
    
 
// Step 4. Set email contents - you can use variables!
mail.setSubject('Research Call Update');
String body = 'Date: ' + newTask.ActivityDate + '<br/>';
body += 'Caller: ' + newTask.Assigned_To_Dupe__c + '<br/>';
body += 'Company Name: ' + newTask.Account_Name_dupe__c + '<br/>';
body += 'Contact Name: ' + newTask.Client_Name__c  + '<br/>';
body += 'Description: ' + newTask.Description + '<br/>';
mail.setHtmlBody(body);

// Step 5. Add your email to the master list
mails.add(mail);    
          
}
// Step 6: Send all emails in the master list
Messaging.sendEmail(mails);
}

Let us know if it helps you.
Ashish
ashish.sharma.devsfdc@gmail.com

All Answers

Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi Michael Haase,

Use below code to avoid calling 'sendEmail' method more than 10 times with in for loop.
Please keep 'SendEmail()' outside of for loop,as there is a limit of 10 invocations per execution context.
 
trigger Individual_SM_Notification_v2 on Task (after insert) {

//Query for Contact    
//Step 1: Create a Set of all Contacts to query
Set<String> allWhoIds = new Set<String>();
for (Task newTask : Trigger.new){
if (newTask.WhoId != null){
allWhoIds.add(newTask.WhoId);
    system.debug('Step 1: ' + newTask.WhoId);
}
}

//Step 2:Query the Contact Ids from the WhoIds (from Step 1)
List <Contact> potentialContacts = [Select Id, Name, Owner.Email, Owner.LastName From Contact Where Id In :allWhoIds];
system.debug('List<Contact> Details: ' + potentialContacts);
   
    
    
//Step 3: Create Map to search Contacts by WhoId
Map<String, String>WhoIdToContactMap = new map<String, String>();
for (Contact c : potentialContacts){
WhoIdToContactMap.put(c.Id, c.Owner.Email);
}

// Create a master list to hold the emails we'll send
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
//Get the matching Contact Owner by the Contact Id
for (task newTask : Trigger.new){
String UserToUpdate = WhoIdToContactMap.get(newTask.WhoId);
System.debug('User to update: ' + UserToUpdate);
      

    
    
    
    
// Step 1: Create a new Email
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();    
    
// Step 2: Set list of people who should get the email
      List<String> sendTo = new List<String>();
      sendTo.add(UserToUpdate);
      mail.setToAddresses(sendTo); 
    System.debug('Step 2:' + sendTo);
    
    
// Step 3: Set who the email is sent from
      mail.setReplyTo('SalesforceAdmin@bcsprime.com');
      mail.setSenderDisplayName('BCS GMIB Research Team'); 
    system.debug('Step 3:' + mail);

// (Optional) Set list of people who should be CC'ed
      List<String> ccTo = new List<String>();
      ccTo.add('mhaase@bcsprime.com');
      mail.setCcAddresses(ccTo);    
    
 
// Step 4. Set email contents - you can use variables!
mail.setSubject('Research Call Update');
String body = 'Date: ' + newTask.ActivityDate + '<br/>';
body += 'Caller: ' + newTask.Assigned_To_Dupe__c + '<br/>';
body += 'Company Name: ' + newTask.Account_Name_dupe__c + '<br/>';
body += 'Contact Name: ' + newTask.Client_Name__c  + '<br/>';
body += 'Description: ' + newTask.Description + '<br/>';
mail.setHtmlBody(body);

// Step 5. Add your email to the master list
mails.add(mail);    
          
}
// Step 6: Send all emails in the master list
Messaging.sendEmail(mails);
}

Let us know if it helps you.
Ashish
ashish.sharma.devsfdc@gmail.com
This was selected as the best answer
Michael HaaseMichael Haase
That worked. Thanks a lot!!!