3

I am using SingleEmailMessage api for sending emails. I want to know the email limit quota usage, so that I can prevent further exceptions. Is there any way to know the quota usage in apex, so that I can handle exception with ease.

1
4

You can use the Limits class to find out how many invocations remain as follows:

Integer remainingInvocations =
    Limits.getLimitEmailInvocations() - Limits.getEmailInvocations();
2
  • That only gives you the limits for the current transaction. – sfdcfox Jan 11 '16 at 19:43
  • 1
    @sfdcfox That's why I linked to another question in the comments. Pretty sure this question has been answered in a couple different spots but didn't spot a definitive dupe off the bat. – Adrian Larson Jan 11 '16 at 19:44
2

A strategy to use would be the following (assuming your APEX is sending one (1) email message; adapt code for more than one accordingly. The key is the method Messaging.reserveSingleEmailCapacity(someInteger) that you invoke before you send.

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
try {
        Messaging.reserveSingleEmailCapacity(1); // SFDC throws exception if no headroom
        email.setToAddresses(...);
        ...
        Messaging.sendEmail(email);
}
catch (HandledException e) {
// do something interesting like set up a retry mechanism for the next day
// by persisting the message to send in some object and then having a daily
// scheduled job resend the message at 0000h
}

There is a related post on this topic by @DougB

UPDATE

Prior to Winter 14, the reserveMassEmailCapacity existed but would throw an unhandled exception, this changed as per the Winter 14 Release Notes page 304

Updated Errors for Email Messaging Methods Errors have changed for the Apex Messaging methods reserveMassEmailCapacity and reserveSingleEmailCapacity, which are used when sending a mass or single email, respectively. If the transaction would cause the organization to exceed its daily email limit, using either of these methods results in a Handled Exception error. (Previously it resulted in a Limit Exception error.) The error that appears is: System.HandledException: The daily limit for the org would be exceeded by this request.

5
  • It looks like the exception from reserveSingleEmailCapacity is uncatchable. That's the answer I linked in the comments. :) – Adrian Larson Jan 12 '16 at 1:42
  • @adrianLarson see my update above – cropredy Jan 12 '16 at 1:52
  • How long is the capacity "reserved" for? Just the transaction context? The full 24 hours? – Adrian Larson Jan 12 '16 at 4:59
  • At most I would think it was the transaction – cropredy Jan 12 '16 at 5:33
  • OP totally accepted the wrong answer on this one. Oops. – Adrian Larson Oct 18 '16 at 18:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.