Repository navigation
feat: add batch email sending to fix Mailgun rate limiting - #11042
ooye-sanket wants to merge 4 commits into
Conversation
- 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
📝 WalkthroughWalkthroughThe 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)
✨ Finishing touches
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. Comment |
Security Scan Results for PRDocker Image Scan Results
Source Code Scan Results🎉 No vulnerabilities found! |
There was a problem hiding this comment.
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.phpevent class now sendssenderEmailandsenderNameat the root level of the payload, but this code still looks for them insidecustomMailOptions. Additionally,replyToEmailandreplyToNamewere 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
📒 Files selected for processing (2)
src/Appwrite/Event/Mail.phpsrc/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
$recipientsarray and explicit$senderEmail/$senderNameproperties provide a clearer structure than the previous$customMailOptionsapproach.
78-104: LGTM - Flexible recipient handling.The dual-format support (associative
email => nameand 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
eventsgeneration viaEvent::generateEventsis correctly retained.src/Appwrite/Platform/Workers/Mails.php (5)
71-78: LGTM - Good observability.Batch mode detection aligns with
Mail.php'sisBatch()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
sendSingleandsendBatch.
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
There was a problem hiding this comment.
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 => nameand indexed[email]formats) is duplicated between lines 174-178 and lines 267-274 insendBatch.🔎 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
📒 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
sendSinglemethod 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
prepareAltBodymethod properly removes style blocks and HTML tags to create a plain-text alternative body, reducing code duplication from the previous implementation.
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
There was a problem hiding this comment.
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
prepareAltBodyhelper 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
📒 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
sendSinglemethod correctly isolates per-recipient logic, properly clears PHPMailer state, uses the sharedprepareAltBodyhelper, and provides recipient-specific context in error messages for better debugging.
233-300: LGTM: Batch sending correctly addresses rate limiting and privacy concerns.The
sendBatchmethod 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.
|
Hi maintainers 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 |
|
Hi Appwrite maintainers This introduces backward-compatible batch email sending to prevent Mailgun rate limiting while preserving existing single-recipient behavior. |
|
Closing as this change targets code that no longer exists on main. Thanks! |
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:
Solution
This PR introduces batch email sending support:
Changes to
Mail.php:$recipientsarray property for batch sendingsetRecipients(),addRecipient(),getRecipients()methodsisBatch()helper to detect batch modepreparePayload()to include recipients array$recipientpropertyChanges to
Mails.php:action()methodsendBatch()method using BCC for efficient batch deliverysendSingle()method for single recipient sendsprepareAltBody()helper to reduce code duplicationHow It Works
For API Providers (like Mailgun):
For SMTP:
Backward Compatibility:
recipientsarray is providedTest Plan
Manual Testing Steps
Example Usage
Single recipient (existing code - still works):
Batch mode (new functionality):
Or using addRecipient():
Considerations
Related PRs and Issues
cc @mountainash - Original issue reporter
Checklist
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.