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
SFDummySFDummy 

After insert sending too many emails

I have a trigger on Account to send email notification after mass update is complete.
But I am getting multiple email notification because Salesforce Trigger is processing 200 at a time. Any suggestions on how I can only send one email instead of multiple (1 for every 200)
trigger AccountTriggers on Account (before Insert, after update, after insert){

  //Email Notification after mass upload Complete 
  if(!recordIds.isEmpty() && recordIds.size() > 100){     
        ASA_SubgroupTrigger_EmailNotification.SendEmailToSalesTeam();
      }        

}
I tried with DbAmp, Apex dataloader. I have over 800 records. I got 5 email notification when I loaded my records.

We are getting weekly data to load into Salesforce. Need to notify sales team after the upload is complete. But the above sample code is generating 5 emails, 1 for every 200 records. I tried is isBatch(), the values is FALSE in this scenario.
Any suggestions ?
 
pconpcon
That's because the isBatch refers to using batch Apex [1], not batch dataloading.  I think you will either have to increase the number of records you send via the dataloader, or change your strategy for sending the emails.  One option could be to create a Custom Setting [2] and when before your first batch is uploaded set a boolean to false for something like has_sent_email__c then if that boolean is false send your email to the sales team.  It would require an additional step in your dataloader process but would be pretty easy to implement.

[1] https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm
[2] https://help.salesforce.com/apex/HTViewHelpDoc?id=cs_about.htm
SFDummySFDummy
In Dataloader I checked "Use Bulk API" Batch size auto updated to 2000. I loaded 1100 Records I still got 6 emails.
pconpcon
The code you have provided above does not make sense because you have recordIds that does not exist.  Also, how does the SendEmailToSalesTeam operate?  Does it work off of the Trigger object or does it just send an email without any context?  If you are using a construct like the following in your code then the 200 per is to be expected.
 
for (List<Account> accountList : Trigger.new) {
    // do something including send email
}

If you are sure that the entire data load is occuring in a single transaction you can always create a class level static variable and use that to "lock" your email notifications for the transaction.  For example

EmailUtils.cls
public class EmailUtils {
    public static Boolean BULK_LOCK = false;
}

Code in trigger
if (!EmailUtils.BULK_LOCK) {
    EmailUtils.BULK_LOCK = true;

    // Code to send emails
}

This will ensure that it only runs once for the entire transaction.