Skip to content

feat: add batch email sending to fix Mailgun rate limiting - #11042

Closed
ooye-sanket wants to merge 4 commits into
appwrite:mainfrom
ooye-sanket:patch-4
Closed

ooye-sanket wants to merge 4 commits into
appwrite:mainfrom
ooye-sanket:patch-4

Conversation

@ooye-sanket

Copy link
Copy Markdown

What does this PR do?

Fixes #11023 - Adds support for batch email sending to prevent hitting Mailgun rate limits when sending to multiple recipients.

Problem

When sending emails to 30+ recipients via Mailgun, Appwrite was making individual API calls for each recipient, causing:

  • Rate limiting by Mailgun (only 20-25 emails delivered out of 30+)
  • Inefficient use of API resources
  • UI showing "sent" status while emails were actually dropped

Solution

This PR introduces batch email sending support:

Changes to Mail.php:

  • Added $recipients array property for batch sending
  • Added setRecipients(), addRecipient(), getRecipients() methods
  • Added isBatch() helper to detect batch mode
  • Updated preparePayload() to include recipients array
  • Maintained full backward compatibility with single $recipient property

Changes to Mails.php:

  • Added batch detection in action() method
  • Implemented sendBatch() method using BCC for efficient batch delivery
  • Extracted sendSingle() method for single recipient sends
  • Added prepareAltBody() helper to reduce code duplication
  • Enhanced logging with batch mode and recipient count tags
  • Handles both API providers (batch mode) and SMTP (individual mode)

How It Works

For API Providers (like Mailgun):

  • Uses BCC to send one email to multiple recipients
  • Maintains privacy (recipients don't see each other)
  • Reduces API calls from N to 1 (where N = number of recipients)

For SMTP:

  • Sends individually as SMTP servers often have lower recipient limits
  • Maintains compatibility with various SMTP providers

Backward Compatibility:

  • Existing single-recipient code continues to work unchanged
  • New batch functionality only activates when recipients array is provided

Test Plan

Manual Testing Steps

  1. Set up Mailgun as messaging provider in Appwrite
  2. Create email message with 30+ recipients using the new batch API
  3. Send email and verify all recipients receive it
  4. Check Mailgun logs - should show 1 API call instead of 30+
  5. Test with SMTP provider to ensure individual sends still work
  6. Test single recipient mode to ensure backward compatibility

Example Usage

Single recipient (existing code - still works):

$mail->setRecipient('[email protected]')
     ->setName('User')
     ->trigger();

Batch mode (new functionality):

$mail->setRecipients([
    '[email protected]' => 'User One',
    '[email protected]' => 'User Two',
    '[email protected]' => 'User Three',
])
->trigger();

Or using addRecipient():

$mail->addRecipient('[email protected]', 'User One')
     ->addRecipient('[email protected]', 'User Two')
     ->trigger();

Considerations

  • Rate Limits: Mailgun supports up to 1,000 recipients per API call
  • SMTP Limits: Most SMTP servers support 50-100 recipients; this PR sends individually for SMTP to avoid issues
  • Privacy: BCC is used so recipients don't see each other's email addresses
  • Logging: Enhanced logging helps track batch operations and troubleshoot issues

Related PRs and Issues

cc @mountainash - Original issue reporter

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

Note to reviewers: This implementation prioritizes backward compatibility while introducing an efficient batch sending mechanism. The approach uses PHPMailer's BCC functionality for API providers and maintains individual sends for SMTP to ensure maximum compatibility.

- Add batch mode detection in action() method
- Implement sendBatch() for efficient BCC-based batch delivery
- Extract sendSingle() method for individual email sending
- Add prepareAltBody() helper to reduce code duplication
- Add comprehensive logging for batch operations
- Handle both API providers (batch) and SMTP (individual) modes
- Maintain backward compatibility with single recipient flow

This prevents rate limiting issues when sending to multiple recipients
by batching them into a single API call instead of making individual
calls that trigger provider rate limits.

Fixes appwrite#11023"
- Add recipients array property for batch email sending
- Add setRecipients(),  addRecipient(), getRecipients()  methods
- Add isBatch() helper method to detect batch mode
- Update preparePayload() to include recipients array
- Update reset() to clear recipients array
- Maintain backward compatibility with single recipient property

Addresses appwrite#11023
@coderabbitai

coderabbitai Bot commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PR adds batch mail support by introducing a recipients array, methods to set/add/get recipients and an isBatch() check in Appwrite\Event\Mail. It replaces the legacy customMailOptions with explicit senderEmail and senderName fields, removes reply-to methods, and updates reset and preparePayload to emit recipients and sender fields. In Appwrite\Platform\Workers\Mails, sending logic was refactored into private helpers (sendSingle, sendBatch, prepareAltBody); the worker now branches for batch vs single sends, enforces a 1000-recipient limit, and logs batch_size/status and recipient_count.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add batch email sending to fix Mailgun rate limiting' accurately and specifically summarizes the main change: introducing batch email sending functionality to address Mailgun rate limits.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, explaining the problem, solution, implementation details, and testing approach.
Linked Issues check ✅ Passed The PR satisfies the core requirement from #11023: implementing batch email sending to reduce API calls from N individual calls to 1, using recipient arrays with API providers, while maintaining backward compatibility.
Out of Scope Changes check ✅ Passed All code changes align with the stated objectives: Mail.php refactoring for batch support, Mails.php batch detection and processing, and helper methods for payload preparation.
Docstring Coverage ✅ Passed Docstring coverage is 93.75% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@ooye-sanket ooye-sanket changed the title Patch 4 feat: add batch email sending to fix Mailgun rate limiting Dec 30, 2025
@github-actions

github-actions Bot commented Dec 30, 2025 •

Copy link
Copy Markdown

Security Scan Results for PR

Docker Image Scan Results

Package Version Vulnerability Severity
libpng 1.6.51-r0 CVE-2025-66293 HIGH
libpng-dev 1.6.51-r0 CVE-2025-66293 HIGH

Source Code Scan Results

🎉 No vulnerabilities found!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Appwrite/Platform/Workers/Mails.php (1)

154-169: Critical: Payload structure mismatch breaks sender customization.

The Mail.php event class now sends senderEmail and senderName at the root level of the payload, but this code still looks for them inside customMailOptions. Additionally, replyToEmail and replyToName were removed from the event class, making lines 163-165 dead code.

🔎 Proposed fix to align with new payload structure
-        $customMailOptions = $payload['customMailOptions'] ?? [];
+        $senderEmail = $payload['senderEmail'] ?? '';
+        $senderName = $payload['senderName'] ?? '';

         // fallback hierarchy: Custom options > SMTP config > Defaults.
-        if (!empty($customMailOptions['senderEmail']) || !empty($customMailOptions['senderName'])) {
-            $fromEmail = $customMailOptions['senderEmail'] ?? $mail->From;
-            $fromName = $customMailOptions['senderName'] ?? $mail->FromName;
+        if (!empty($senderEmail) || !empty($senderName)) {
+            $fromEmail = $senderEmail ?: $mail->From;
+            $fromName = $senderName ?: $mail->FromName;
             $mail->setFrom($fromEmail, $fromName);
         }

-        if (!empty($customMailOptions['replyToEmail']) || !empty($customMailOptions['replyToName'])) {
-            $replyTo = $customMailOptions['replyToEmail'] ?? $replyTo;
-            $replyToName = $customMailOptions['replyToName'] ?? $replyToName;
-        } elseif (!empty($smtp)) {
+        if (!empty($smtp)) {
             $replyTo = !empty($smtp['replyTo']) ? $smtp['replyTo'] : ($smtp['senderEmail'] ?? $replyTo);
             $replyToName = $smtp['senderName'] ?? $replyToName;
         }
🧹 Nitpick comments (1)
src/Appwrite/Platform/Workers/Mails.php (1)

103-104: Spurious whitespace.

Line 103 appears to be whitespace-only. Consider removing the stray whitespace to keep the diff clean.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44ec8de and 491ca80.

📒 Files selected for processing (2)
  • src/Appwrite/Event/Mail.php
  • src/Appwrite/Platform/Workers/Mails.php
🧰 Additional context used
🧬 Code graph analysis (1)
src/Appwrite/Event/Mail.php (1)
src/Appwrite/Event/Event.php (3)
  • Event (10-678)
  • generateEvents (492-604)
  • getEvent (131-134)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: scan
🔇 Additional comments (10)
src/Appwrite/Event/Mail.php (5)

10-21: LGTM - Clean property declarations for batch support.

The new $recipients array and explicit $senderEmail/$senderName properties provide a clearer structure than the previous $customMailOptions approach.


78-104: LGTM - Flexible recipient handling.

The dual-format support (associative email => name and indexed ['email']) documented in the docblock provides good flexibility while maintaining backward compatibility.


116-124: LGTM!

Clean batch detection logic.


504-517: LGTM - Comprehensive reset.

All new properties (recipients, senderEmail, senderName) are properly cleared alongside existing fields.


525-543: LGTM - Updated payload structure.

The payload now includes batch recipients and explicit sender fields. The events generation via Event::generateEvents is correctly retained.

src/Appwrite/Platform/Workers/Mails.php (5)

71-78: LGTM - Good observability.

Batch mode detection aligns with Mail.php's isBatch() logic, and the logging tags (batch_mode, recipient_count) provide useful operational visibility.


172-185: Sensible branching strategy for batch sends.

The design correctly uses BCC batching for API providers (avoiding rate limits per issue #11023) while falling back to individual sends for SMTP to respect server limits.

Minor consideration: The SMTP batch loop (lines 176-182) will abort on the first failure. If partial delivery is unacceptable, this is fine. Otherwise, consider collecting failures and continuing.


200-231: LGTM - Clean single-send helper.

The recipient clearing before each send enables safe reuse in the SMTP batch loop. Error messages include recipient context for debugging.


262-276: Verify: Sender receives copy of every batch email.

Line 266 sets the sender as the primary To: recipient, meaning the sender's address will receive every batch email. This is noted in the docblock as intentional for SMTP envelope validity, but may be unexpected behavior.

Consider using undisclosed-recipients:; as the To address if the email provider supports it, or document this behavior clearly for users.


309-316: LGTM - Good helper extraction.

The plain-text generation logic (strip styles → strip tags → trim) is correctly implemented and reduces duplication between sendSingle and sendBatch.

Replace customMailOptions with direct senderEmail/senderName access and Remove dead code for replyToEmail/replyToName (not in Mail.php), also Remove spurious whitespace at line 103

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/Appwrite/Platform/Workers/Mails.php (2)

103-103: Whitespace-only change.


174-178: Consider extracting recipient normalization into a helper.

The recipient array normalization logic (handling both associative email => name and indexed [email] formats) is duplicated between lines 174-178 and lines 267-274 in sendBatch.

🔎 Proposed refactor to reduce duplication

Add a private helper method:

/**
 * Normalize recipients array to ensure consistent email => name format
 * Handles both ['email' => 'name'] and ['email'] formats
 *
 * @param array $recipients
 * @return array Normalized array of email => name pairs
 */
private function normalizeRecipients(array $recipients): array
{
    $normalized = [];
    foreach ($recipients as $email => $name) {
        if (is_numeric($email)) {
            $email = $name;
            $name = '';
        }
        $normalized[$email] = $name;
    }
    return $normalized;
}

Then simplify both locations:

-foreach ($recipients as $email => $recipientName) {
-    if (is_numeric($email)) {
-        $email = $recipientName;
-        $recipientName = '';
-    }
+foreach ($this->normalizeRecipients($recipients) as $email => $recipientName) {
     // ... rest of logic
 }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 491ca80 and be8b9df.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Workers/Mails.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: scan
🔇 Additional comments (4)
src/Appwrite/Platform/Workers/Mails.php (4)

71-78: LGTM! Clear batch mode detection and logging.

The batch mode detection correctly identifies when recipients are provided, and the logging tags (batch_mode, recipient_count) will help with monitoring and debugging batch email operations.


154-169: LGTM! Sender configuration handles fallback correctly.

The sender email/name configuration properly falls back to existing mail object values when payload values are empty, and the reply-to setup maintains backward compatibility with SMTP configuration.


186-229: LGTM! Single-recipient sending is well-structured.

The sendSingle method properly clears previous state, configures the recipient, prepares the alt body using the new helper, handles attachments, and provides improved error messages with recipient context.


300-314: LGTM! AltBody preparation is correct.

The prepareAltBody method properly removes style blocks and HTML tags to create a plain-text alternative body, reducing code duplication from the previous implementation.

Comment thread src/Appwrite/Platform/Workers/Mails.php Resolved
Comment thread src/Appwrite/Platform/Workers/Mails.php Resolved
Add validation to prevent exceeding Mailgun's 1000 recipient limit and Use system email address instead of sender for batch 'To' field. Prevents sender from receiving copies of all batch emails

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/Appwrite/Platform/Workers/Mails.php (2)

170-186: Validation and routing logic correctly addresses Mailgun rate limiting.

The 1000-recipient validation guard prevents API errors, and the routing logic appropriately branches between API batch sending (one call) and SMTP individual sends (avoiding SMTP limits). The recipient normalization at lines 177-180 correctly handles both associative and indexed arrays.

Optional: Extract recipient normalization to reduce duplication

The recipient array normalization logic (lines 177-180 and lines 270-273) is duplicated. Consider extracting it:

private function normalizeRecipient($email, $recipientName): array
{
    if (is_numeric($email)) {
        return [$recipientName, ''];
    }
    return [$email, $recipientName];
}

Then use it in both loops:

 foreach ($recipients as $email => $recipientName) {
-    if (is_numeric($email)) {
-        $email = $recipientName;
-        $recipientName = '';
-    }
+    [$email, $recipientName] = $this->normalizeRecipient($email, $recipientName);
     $this->sendSingle($mail, $email, $recipientName, $subject, $body, $attachment);
 }

302-316: LGTM: AltBody generation is adequate for email fallback.

The prepareAltBody helper correctly strips HTML to provide plain-text alternatives. The regex pattern removes <style> blocks before general tag stripping, which is appropriate for email content.

Optional: Consider HTML parsing library for robustness

The regex-based style removal works for typical email templates but may not handle all edge cases (malformed HTML, CDATA blocks, etc.). For greater robustness, consider using PHP's DOMDocument or a library like HTML Purifier:

private function prepareAltBody(string $body): string
{
    $dom = new \DOMDocument();
    @$dom->loadHTML($body, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    
    // Remove style elements
    $styles = $dom->getElementsByTagName('style');
    foreach (iterator_to_array($styles) as $style) {
        $style->parentNode->removeChild($style);
    }
    
    return trim(strip_tags($dom->saveHTML()));
}

This is a minor enhancement—the current regex approach is acceptable for email fallback content.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be8b9df and aebb6d5.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Workers/Mails.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: scan
🔇 Additional comments (5)
src/Appwrite/Platform/Workers/Mails.php (5)

71-78: LGTM: Batch mode detection and logging.

The batch mode detection logic is sound—checking for non-empty recipients array is appropriate, and the logging additions provide good observability for batch operations.


154-162: LGTM: Sender customization with proper fallback.

The fallback hierarchy (custom sender → existing mail config) is correctly implemented, maintaining backward compatibility while enabling per-message sender customization.


164-169: LGTM: Reply-to configuration.

The reply-to fallback chain correctly prioritizes SMTP-specific configuration while maintaining sensible defaults.


188-231: LGTM: Clean single-recipient send implementation.

The sendSingle method correctly isolates per-recipient logic, properly clears PHPMailer state, uses the shared prepareAltBody helper, and provides recipient-specific context in error messages for better debugging.


233-300: LGTM: Batch sending correctly addresses rate limiting and privacy concerns.

The sendBatch method effectively solves Issue #11023 by consolidating recipients into a single API call using BCC. Line 266 correctly uses the system email as the envelope recipient (satisfying API requirements without sending copies to the sender—this addresses the prior review concern). The comprehensive logging (batch_size, batch_status) aids observability, and error messages include batch context.

@ooye-sanket ooye-sanket mentioned this pull request Dec 30, 2025
2 tasks done
@ooye-sanket

ooye-sanket commented Dec 31, 2025 •

Copy link
Copy Markdown
Author

Hi maintainers
This PR is ready for review and merge.

It addresses Mailgun rate limiting by introducing backward-compatible batch email sending, with all checks passing and CodeRabbit review completed.

Would appreciate a review and approval when you get a chance

@ooye-sanket

Copy link
Copy Markdown
Author

Hi Appwrite maintainers
Friendly ping on this PR. All feedback has been addressed, CodeRabbit review is complete, and checks are passing.

This introduces backward-compatible batch email sending to prevent Mailgun rate limiting while preserving existing single-recipient behavior.
Would appreciate a review and approval when you get a chance. Thanks!

@HarshMN2345

Copy link
Copy Markdown
Member

Closing as this change targets code that no longer exists on main. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mailgun Rate Limiter [possibly] hit

2 participants