[SalesForce] Best Practice for Sending Emails via Apex

I'm playing around in my Dev org and am using a trigger to send a basic e-mail to System Admins when an account is created as follows:

private static void doNotifyAdmin(List<Account> acc) {
  Id p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id;
  List<String> toAddresses = new List<String>();

  for (User u : [SELECT Email FROM User WHERE ProfileId = :p]) {
    toAddresses.add(u.Email);
  }

  for (Account a : acc) {
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    email.setSubject('New Account Created!');
    email.setToAddresses(toAddresses);
    email.setHTMLBody('The account: ' + a.Name + ' was added to the system!');

    Messaging.SendEmailResult[] r = Messaging.sendEmail(
      new Messaging.SingleEmailMessage[] {
        email
      }
    );
  }
}

This all works fine, but I was wondering whether or not I'm doing it to best practice, particularly in the for loop sending the SingleEmailMessage.

In debug logs I noticed the following line:

Number of Email Invocations: 1 out of 10

As I'm the only account in the dev org, this isn't a big deal but if I were to send e-mails to 20 people in this way, for instance, would this fail? Or would it be fine given I'm querying addresses to send to in the toAddresses list?

Just curious to know if I'm engaging in best practices here!

Thanks!

Best Answer

If I were the Sysad, I would want to only get a summary of all Accounts created once per day (or maybe once per x hours) rather than be spammed every time an Account was created.

In this model, you would use a scheduled APEX class to run every x hours, looking for Accounts where some field has_sysad_been_notified__c is false. Collect all the account names into the body of the email, send a message whose subject contains the number of accounts, and then update the Account's has_sysad_been_notified__c to true. Alternatively, you could use Tasks under the Account to record whether notification has been sent and when (probably a better idea the more I think about it)

In all cases, when using apex outbound email, reserve how many you intend to send and handle any exceptions with a retry model (where the scheduled class comes in useful). Orgs tend to have many outbound email processes over time and it is easy to hit the daily limit.

Related Topic