Overview
This rule flags Apex code that calls Messaging.sendEmail() inside a loop. While it's common to send emails in response to record changes or user actions, invoking this method repeatedly within a loop is inefficient and can easily exceed Salesforce’s governor limits for email operations.
Code Reviews classifies this as an Error because it risks platform exceptions and poor performance, especially when handling large data volumes or operating within triggers, Flows, or batch jobs.
Why This Matters
Placing sendEmail() inside loops can:
Hit the email governor limit (maximum 10
sendEmailcalls per transaction)Cause runtime exceptions, interrupting business processes or user actions
Slow down execution due to repeated processing and server calls
Result in incomplete communication, especially in bulk operations
Salesforce’s bulk-safe development model requires batching such operations to avoid these risks.
What Triggers This Rule
Code Reviews flags Apex code where:
Messaging.sendEmail()is called within any loop (for,while, etc.)Each iteration of the loop sends an individual email
Recommended Approach
Build a collection of Messaging.SingleEmailMessage objects during the loop, then send them all at once outside the loop using a single sendEmail() call.
Summary
Avoid calling Messaging.sendEmail() inside loops to prevent exceeding Salesforce's email limits and ensure your automation is scalable. Always prepare emails in a collection and send them in a single operation. Code Reviews flags this as an Error to promote bulk-safe, efficient communication handling.
