Symfony 8.2 is a big release for emails. We already introduced provider-hosted templates and tracking control, PGP/MIME signed and encrypted emails and ten new Mailer and Notifier bridges. This article showcases the rest of the new features of the Mailer and Webhook components.

Rate Limited Mailer Transports

Fritz Michael Gschwantner
Contributed by Fritz Michael Gschwantner in #59985

Many email providers limit how many emails you can send per hour, and some of them suspend your account if you go over that limit. If you send emails asynchronously, you can rate limit the Messenger transport, but that limit applies to all your emails. This doesn't work when your application uses several mailer transports with different limits.

In Symfony 8.2, each mailer transport can define its own rate limiter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# config/packages/mailer.yaml
framework:
    mailer:
        transports:
            newsletter:
                dsn: '%env(MAILER_NEWSLETTER_DSN)%'
                rate_limiter: newsletter_emails
            billing:
                dsn: '%env(MAILER_BILLING_DSN)%'
                rate_limiter: billing_emails
            # transports without a rate limit keep using the short syntax
            alerts: '%env(MAILER_ALERTS_DSN)%'

    rate_limiter:
        newsletter_emails:
            policy: fixed_window
            limit: 500
            interval: '60 minutes'
        billing_emails:
            policy: fixed_window
            limit: 50
            interval: '60 minutes'

When a transport reaches its limit, sending an email throws a RateLimitExceededException. If you send emails asynchronously with Messenger, Symfony retries the email as soon as the limiter accepts it again, and the worker keeps sending the emails of the other transports in the meantime. If you send emails synchronously, your application must catch that exception. Reaching the limit is not a transport failure, so the failover transport doesn't switch to the next transport when it happens.

Configuring the SMTP Timeout in the DSN

anktx
Contributed by anktx in #65420

The SMTP transport uses the default_socket_timeout PHP ini option as its timeout, which is 60 seconds by default. That's too long for a worker waiting for a mail server that doesn't respond, and there was no way to change it for a single transport. Symfony 8.2 adds a timeout option to the smtp:// and smtps:// DSNs:

1
2
# .env
MAILER_DSN=smtp://user:pass@smtp.example.com:587?timeout=10

The value is a number of seconds (it can be a decimal number like 2.5) and it applies both to the connection and to the reads and writes that follow it.

Address Groups in Email Headers

Florent Morselli
Contributed by Florent Morselli in #65771

Email standards allow a header like To to contain a group: a name followed by a list of addresses, which can be empty. This is how newsletters display To: undisclosed-recipients:; while the real recipients stay hidden in the Bcc header. Symfony 8.2 adds a Group class to create them:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Group;

$email = (new Email())
    ->from('newsletter@example.com')
    ->bcc('alice@example.com', 'bob@example.com')
    ->subject('Weekly digest')
    ->text('...');

// To: undisclosed-recipients:;
$email->getHeaders()->addMailboxListHeader('To', [new Group('undisclosed-recipients')]);

// groups can list their members and be mixed with regular addresses
// Cc: Board: chair@example.com, Jane Roe <cfo@example.com>;, observer@example.com
$email->getHeaders()->addMailboxListHeader('Cc', [
    new Group('Board', ['chair@example.com', new Address('cfo@example.com', 'Jane Roe')]),
    'observer@example.com',
]);

Groups are added through the headers because methods like to() and cc() still accept only addresses. Methods like getTo() keep returning a list of Address objects, including the members of the groups, so the code that reads the recipients doesn't need any change. Groups are supported in the To, Cc, Bcc and Reply-To headers and, as defined by RFC 6854, in From.

Note

Groups only work with SMTP transports. API transports read the list of addresses, so they send the members of the group but not its name.

Binary Content-Transfer-Encoding

Ousama Ben Younes
Contributed by Ousama Ben Younes in #64066

Symfony encodes the parts of an email with quoted-printable, base64 or 8bit. Some systems that exchange MIME messages over HTTP or other custom channels expect the raw contents instead. In Symfony 8.2 you can use binary as the encoding of a part to send its contents untouched:

1
2
3
use Symfony\Component\Mime\Part\DataPart;

$part = new DataPart(fopen($path, 'r'), 'report.pdf', 'application/pdf', 'binary');

Symfony never selects this encoding on its own; you must ask for it explicitly.

Caution

SMTP can't carry binary contents unless the server supports the BINARYMIME extension, and Symfony doesn't check that for you. Use this encoding only when you control how the message is delivered.

Standard Webhooks Signatures

Quentin Dequippe Nicolas Grekas
Contributed by Quentin Dequippe and Nicolas Grekas in #62958

The webhooks sent by the Webhook component are signed with a format specific to Symfony, so applications not built with Symfony have to write their own code to verify them. Standard Webhooks is a specification followed by many companies to sign webhooks, with libraries to verify them in most programming languages.

In Symfony 8.2, the webhooks that you send include a Webhook-Timestamp header and a new option lets you sign and verify them with the Standard Webhooks format:

1
2
3
4
5
6
7
8
# config/packages/webhook.yaml
framework:
    webhook:
        # 'legacy' (default), 'standard' or 'transitional'
        signature_format: standard
        # reject webhooks whose timestamp differs more than
        # this number of seconds from now (default: 300)
        timestamp_tolerance: 120

The standard format signs the ID, the timestamp and the body of the webhook. This allows Symfony to reject old webhooks that someone captured and sent again. The event name is no longer sent in a header, because that signature doesn't cover headers; it's sent in the type key of the payload instead.

The transitional format sends both signatures and accepts either of them. Use it to migrate applications without downtime: switch the receivers to transitional, then the senders to standard and, finally, the receivers to standard.

Blocking Webhooks to Private Networks

Nicolas Grekas
Contributed by Nicolas Grekas in #65750

The URLs where your application sends webhooks are usually provided by third parties. A malicious subscriber can register a URL that points to a server inside your own network to make your application send requests to it. Symfony 8.2 adds an option to refuse those URLs:

1
2
3
4
5
6
7
# config/packages/webhook.yaml
framework:
    webhook:
        no_private_network:
            enabled: true
            # optional: private IPs or subnets that can still receive webhooks
            allow_list: ['10.0.5.0/24']

This option wraps the HTTP client that sends the webhooks with the NoPrivateNetworkHttpClient, so it also protects against redirects and DNS tricks. It only affects webhooks; the rest of the HTTP requests of your application keep working as before. The option is disabled by default because many applications send webhooks to services in their own network.

There's also a new framework.webhook.http_client option to set the ID of the HTTP client service used to send webhooks.

Repeatable Remote Event Consumer Attribute

Gabriel Ostrolucký
Contributed by Gabriel Ostrolucký in #63698

Some applications receive webhooks from several accounts of the same service (e.g. one Stripe account per country). Each account needs its own entry in the webhook routing because it has a different secret, but all of them are processed in the same way. In Symfony 8.2, the #[AsRemoteEventConsumer] attribute is repeatable, so a single class can consume the events of all those entries:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/Webhook/StripeWebhookConsumer.php
namespace App\Webhook;

use Symfony\Component\RemoteEvent\Attribute\AsRemoteEventConsumer;
use Symfony\Component\RemoteEvent\Consumer\ConsumerInterface;
use Symfony\Component\RemoteEvent\RemoteEvent;

#[AsRemoteEventConsumer('stripe-us')]
#[AsRemoteEventConsumer('stripe-eu')]
final class StripeWebhookConsumer implements ConsumerInterface
{
    public function consume(RemoteEvent $event): void
    {
        // ...
    }
}

SMS Engagement Events

Ousama Ben Younes
Contributed by Ousama Ben Younes in #65038

The SmsEvent class tells you if an SMS was delivered or failed. Symfony 8.2 adds two event names to know what the recipient did with the message: SmsEvent::CLICKED (the recipient clicked a link of the message) and SmsEvent::UNSUBSCRIBED (the recipient asked to stop receiving messages):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use Symfony\Component\RemoteEvent\Attribute\AsRemoteEventConsumer;
use Symfony\Component\RemoteEvent\Consumer\ConsumerInterface;
use Symfony\Component\RemoteEvent\Event\Sms\SmsEvent;
use Symfony\Component\RemoteEvent\RemoteEvent;

#[AsRemoteEventConsumer('sweego')]
final class SmsWebhookConsumer implements ConsumerInterface
{
    public function consume(RemoteEvent $event): void
    {
        if (!$event instanceof SmsEvent) {
            return;
        }

        match ($event->getName()) {
            SmsEvent::UNSUBSCRIBED => $this->removeFromSmsCampaigns($event->getRecipientPhone()),
            SmsEvent::CLICKED => $this->trackClick($event->getId()),
            default => null,
        };
    }

    // ...
}

For now, the Sweego bridge is the only one that maps its webhooks to these new events.

Published in #Living on the edge