Skip to content

fix(messaging): refuse undeliverable email input with a typed exception - #321

Merged
ChiragAgg5k merged 6 commits into
mainfrom
fix/messaging-invalid-recipients
Sep 22, 2026
Merged

ChiragAgg5k merged 6 commits into
mainfrom
fix/messaging-invalid-recipients

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Why

Resend answered Invalid to field for 269 cloud mails over two weeks (CLOUD-3QX0). Sampling the events gave two causes:

  • recipients at example.com or at domains with no real TLD (c.c, a.i, gyung.me976153), which no provider can route to. Resend blocks reserved domains with a 422 by policy.
  • real gmail.com addresses whose display name carried a comma or angle bracket. The Resend and Mailgun adapters interpolated Name <email> unquoted, so the name broke the header grammar.

Every one of these reached the provider, cost a request, and came back as free-form text that Appwrite had to pattern-match to decide whether to retry.

What

  • Messages\Email validates every to, cc, bcc, from and reply-to address (syntax plus a real TLD) and rejects display names with control characters at construction. Specials such as <, , and " are allowed and quoted later.
  • Adapter\Email::formatAddress() (moved from SES) renders addresses per RFC 5322 for Resend, Mailgun and SES. "Doe, John <JD>" <[email protected]> instead of a malformed header.
  • The Resend adapter maps a 422 (Resend refusing the request as malformed: an address it cannot route, a domain it blocks by policy) to the typed exception with the provider's own message, so which domains are undeliverable stays the provider's decision rather than a hard-coded list here. On the per-recipient path a 422 remains a per-recipient failure when several recipients are sent, so the rest still deliver.
  • Exception\InvalidArgumentException extends the SPL one, so existing catches keep working. getType() returns a constant (recipient_malformed, recipient_domain_invalid, provider_rejected, name_malformed, sender_malformed, too_many_recipients, ...) and getValue() the offending input. Adapter::send() and Messages\Push use it for their existing checks.
  • Mailgun's Reply-To header was sent as a value-less form entry; it is now h:Reply-To => ....

Tests

tests/Messaging/Messages/EmailTest.php covers each type, and ResendRoutingTest asserts the quoted to, from, reply_to and cc payload and that a 422 from Resend surfaces as the typed exception. Each new test was run against the previous production code and fails there.

Usage

Building a message with input no provider can deliver throws before anything is sent:

use Utopia\Messaging\Exception\InvalidArgumentException;
use Utopia\Messaging\Messages\Email;

try {
    $message = new Email(
        to: [['email' => '[email protected]', 'name' => "John\r\nBcc: [email protected]"]],
        subject: 'Welcome',
        content: '<p>Hi</p>',
        fromName: 'Appwrite',
        fromEmail: '[email protected]',
    );
} catch (InvalidArgumentException $exception) {
    $exception->getType();  // 'recipient_domain_invalid'
    $exception->getValue(); // '[email protected]'
}

A request Resend refuses as malformed surfaces the same way, carrying Resend's message:

$message = new Email(to: ['[email protected]'], subject: 'Welcome', content: 'Hi', fromName: 'Appwrite', fromEmail: '[email protected]');

try {
    new Resend('re_key')->send($message);
} catch (InvalidArgumentException $exception) {
    $exception->getType();    // 'provider_rejected'
    $exception->getValue();   // '[email protected]'
    $exception->getMessage(); // 'Invalid `to` field. The email address needs to follow ...'
}

Display names with specials are quoted for the provider instead of breaking the header:

$message = new Email(
    to: [['email' => '[email protected]', 'name' => 'Doe, John <JD>']],
    subject: 'Welcome',
    content: 'Hi',
    fromName: 'Acme "Labs"',
    fromEmail: '[email protected]',
);

// Resend payload
// "to":   ["\"Doe, John <JD>\" <[email protected]>"]
// "from": "\"Acme \\\"Labs\\\"\" <[email protected]>"

A worker maps the type to its own handling instead of matching the provider's message text:

try {
    $adapter->send($message);
} catch (InvalidArgumentException $exception) {
    Span::add('mail.status', 'skipped');
    Span::add('mail.error', $exception->getType());

    return; // bad input: do not retry
}

Follow-up in Appwrite

The cloud Mails worker and the CE Messaging worker should catch Utopia\Messaging\Exception\InvalidArgumentException, skip without retry, and record the type on the span. That replaces the string matching in isRetryableError() for this class of failure.

Resend answered "Invalid `to` field" for 269 cloud mails in two weeks. Most were recipients at example.com or at domains with no real TLD (c.c, a.i), which no provider can route to; the rest were real addresses whose display name carried a comma or angle bracket that the unquoted `Name <email>` rendering turned into a malformed header. Every one reached the provider, cost a request, and came back as free-form text that callers had to pattern-match to decide whether to retry.

Address syntax and display names are now checked when the message is built, reserved domains are refused by the hosted adapters before a request is spent (SMTP and Mock keep accepting them for local catchers), and display names are quoted per RFC 5322 by a formatter shared by Resend, Mailgun and SES. All of these throw `Exception\InvalidArgumentException`, a subclass of the SPL one so existing catches keep working, carrying a type constant and the offending value so callers can map the failure without parsing the message.

Mailgun's Reply-To header was sent as a value-less form entry rather than `h:Reply-To => ...`; fixed while routing it through the formatter.
@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no outstanding blocking or non-blocking defect was found in the current changes.

Summary

This PR introduces typed invalid-input failures for messaging, validates email addresses and display names before delivery, centralizes RFC 5322 address formatting, corrects Mailgun Reply-To serialization, and maps Resend 422 responses to the typed exception.

  • The changes since the previous review only convert PHPUnit data providers from returned arrays to generators.
  • The revised providers remain compatible with the repository’s PHPUnit setup.
  • Previously identified Reply-To, exception-classification, and test-quality concerns are resolved.

Reviews (5) · Last reviewed commit: "style(messaging): yield data provider ca..."

…checking domains

Which domains a provider refuses is the provider's policy, not something to mirror in a hard-coded list that drifts. Resend already answers 422 for a recipient it cannot route to, so the adapter maps that refusal to the typed exception with the provider's own message. On the per-recipient path a 422 stays a per-recipient failure when there are several recipients, so the rest still deliver.
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@greptile review

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@greptile review

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@greptile review

@ChiragAgg5k
ChiragAgg5k merged commit 3128570 into main Sep 22, 2026
6 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/messaging-invalid-recipients branch September 22, 2026 11:38
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.

2 participants