Skip to main content

Code reviews rule: Apex Send Email Restriction

Written by David Martin
Updated this week

Apex Send Email Restriction

Why is this an issue?

When Messaging.sendEmail() is called from methods that are unconditionally reachable from external entry points (such as @AuraEnabled methods), attackers could potentially abuse this functionality to send emails through your org. This could lead to:

  • Email quota exhaustion: Salesforce orgs have daily email limits. Unrestricted access to email sending could exhaust these limits, preventing legitimate business emails.

  • Spam abuse: Your org's email infrastructure could be used to send unsolicited messages.

  • Reputation damage: If your org is used to send spam, your domain's email reputation could suffer.

Examples

Example of incorrect code:

public class EmailService {
@AuraEnabled
public void sendEmail() {
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
mail.setSenderDisplayName('System Admin');
Messaging.MassEmailMessage[] messages = new Messaging.MassEmailMessage[] { mail };
Messaging.sendEmail(messages, true);
}
}

Example of correct code:

public class EmailService {
@AuraEnabled
public void sendEmail() {
// Guard against unauthorized use
if (!canUserSendEmail()) {
return;
}

Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
mail.setSenderDisplayName('System Admin');
Messaging.MassEmailMessage[] messages = new Messaging.MassEmailMessage[] { mail };
Messaging.sendEmail(messages, true);
}

private Boolean canUserSendEmail() {
// Implement appropriate authorization check
return FeatureManagement.checkPermission('Send_Bulk_Email');
}
}

How can I fix violations?

Add authorization or validation logic before the sendEmail() call to ensure it cannot be reached unconditionally from external entry points:

  1. Add a guard clause at the start of the method that returns early if the user is not authorized

  2. Wrap the email sending logic inside a conditional block

  3. Move the sendEmail() call to a private method that is only called after validation

When should I disable this rule?

You may want to dismiss this issue if:

  • The method is intentionally designed to send emails to any caller (e.g., a public contact form handler with rate limiting implemented elsewhere)

  • You have implemented rate limiting or abuse prevention at a different layer (e.g., Flow or platform events)

Resources

Did this answer your question?