I don't know, how to fix it: my messages are in List.


public with sharing class Helper {

public static void afterInsert(List<P__c> newList, Map<ID, P__c> newMap){

    List<Id> userIds = new List<Id>();
    EmailTemplate emailTemplate = [SELECT Id FROM emailTemplate WHERE Name = 'Email'];
    Messaging.Email[] messages = new Messaging.Email[0];

    for(User u : [SELECT Id FROM User WHERE UserRole.Name = 'Manager']){

    for(P__c p : newList){

        Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
    mail.templateId = emailTemplate.Id;
        mail.targetObjectIds = userIds;
        mail.saveAsActivity = false;


trigger EmailTrigger on P__c (after insert) {

if (Trigger.isAfter && Trigger.isInsert) {
    Helper.afterInsert(Trigger.new, Trigger.newMap);


static void sendEmailBulkTest(){
    insert createUser();

    for(Integer i=0; i<11; i++){
        insert p();
    Integer emailInvocations = Limits.getEmailInvocations();
    system.assertEquals(emailInvocations, 11);


And I get msg "System.LimitException: Too many Email Invocations: 11". How can I fix it?

1 Answer 1


Your entire test method is treated as a single transaction. Since you have the insert inside the for loop, you are executing sendMail 11 times in this single transaction, and thus you get the error.

You need to create a list of P__c records and then insert the list outside the for loop.

  • But if I add it into the list in test method, I'll need to write System.assertEquals(emailInvocations, 1); Is it bulk too? Sep 15, 2018 at 4:22
  • Yes you will, and presumably that is what the test aims to show that when may records are added only one send is done (rather than a send per record). By the way, I couldn't use an @YourName in this comment so you might change YourName to something that this mechanism works for.
    – Keith C
    Sep 15, 2018 at 10:24

You must log in to answer this question.

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