# Symfony

Send a Symfony app's mail through Sendora with Symfony Mailer, take every webhook as a remote event, and develop against a test server.

The PHP SDK, `sendora/sendora-php`, has a transport for Symfony Mailer and a request parser for Symfony's Webhook component. With both, a Symfony app sends its mail through the API, and each webhook reaches the app as a remote event. They run on Symfony 6.4 and 7.4 with PHP 8.2 or newer, and on Symfony 8 with PHP 8.4 or newer.

## Before you start

- A [server key](https://sendora.se/docs/keys), which you create on the server's **API keys** tab in the dashboard. A [test server](https://sendora.se/docs/test-servers)'s key works before Sendora approves your account, and it delivers nothing.
- A [verified sending domain](https://sendora.se/docs/domains) for the From address. A test server checks the domain too.

## Install

```sh
composer require sendora/sendora-php symfony/mailer symfony/webhook
```

Symfony Flex adds the route `/webhook/{type}` with `symfony/webhook`. Without Flex, import `@FrameworkBundle/Resources/config/routing/webhook.php` under the prefix `/webhook` in `config/routes.yaml`, or `webhook.xml` before Symfony 7.3.

## Settings

The settings take two variables and two files:

- `.env.local` on your machine, and the production environment, set the variables.
- `config/packages/mailer.yaml` sends the app's mail through the API.
- `config/packages/sendora.yaml`, a file you add, registers the transport, the parser and a client.

Set the server key and the webhook's secret in `.env.local`, which git ignores, so the key stays out of the repository. You get the secret once you create the webhook, as [Webhooks](#webhooks) below shows.

```bash
SENDORA_API_TOKEN=sk_…
SENDORA_WEBHOOK_SECRET=whsec_…
```

In `config/packages/mailer.yaml`, set the DSN. It takes the place of `%env(MAILER_DSN)%`, so the key lives in one variable:

```yaml
framework:
    mailer:
        dsn: 'sendora://%env(SENDORA_API_TOKEN)%@default'
```

Then add `config/packages/sendora.yaml`:

```yaml
framework:
    webhook:
        routing:
            sendora:
                service: sendora.webhook_parser
                secret: '%env(SENDORA_WEBHOOK_SECRET)%'

services:
    sendora.transport_factory:
        class: Sendora\Mailer\SendoraTransportFactory
        parent: mailer.transport_factory.abstract
        tags: ['mailer.transport_factory']

    sendora.webhook_parser:
        class: Sendora\Mailer\Webhook\SendoraRequestParser

    Sendora\Sendora:
        arguments:
            $token: '%env(SENDORA_API_TOKEN)%'
            $logger: '@logger'
```

- `sendora://`, short for `sendora+api://`, is the SDK's transport, with the key as its user. `?stream=<stream id>` after `default` sends on a [stream](https://sendora.se/docs/streams) other than the server's default.
- The routing sends each delivery that reaches `/webhook/sendora` to the parser, which checks its signature with the secret. A delivery is one post of one event to your webhook.
- `Sendora\Sendora` is the API's client, for every call beyond sending, such as reading a message or fetching received mail. Autowiring hands it to any service that takes it.

## Send mail

Send with Symfony's `MailerInterface`. `TagHeader` and `MetadataHeader` set the message's tag and metadata in Sendora, as in `src/Mail/OrderMailer.php`:

```php
<?php

namespace App\Mail;

use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

final class OrderMailer
{
    public function __construct(
        private readonly MailerInterface $mailer,
    ) {}

    public function shipped(
        string $address,
        string $orderId,
    ): void {
        $email = (new Email())
            ->from(new Address(
                'no-reply@example.se',
                'Example AB',
            ))
            ->to($address)
            ->subject('Your order has shipped')
            ->text("Order {$orderId} is on its way.");
        // The message's tag and metadata in Sendora.
        $email->getHeaders()
            ->add(new TagHeader('order-shipped'))
            ->add(
                new MetadataHeader('order_id', $orderId),
            );

        $this->mailer->send($email);
    }
}
```

- A message has one tag. Two different tags fail the send before anything goes out.
- Attachments, inline images, Cc, Bcc and Reply-To go through as Symfony sets them. The PHP SDK's README maps each part of a message to the send.
- Set the header `X-Sendora-Idempotency-Key` from an id of your own, such as the order's, so that a retry does not send the mail twice. A mail that renders differently on the retry fails with `idempotency_key_mismatch`, and does not go again.
- A failed send throws a `TransportException`, whose previous exception is the SDK's. Messenger retries a mail that fails in its worker.

Symfony's `SentMessageEvent` carries Sendora's id for each message. It fires in the process that sends the mail: Messenger's worker when the app sends mail through Messenger, or else the process that calls `send()`. A listener in `src/Mail/LogSendoraId.php` reads it:

```php
<?php

namespace App\Mail;

use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Mailer\Event\SentMessageEvent;

#[AsEventListener]
final class LogSendoraId
{
    public function __construct(
        private readonly LoggerInterface $logger,
    ) {}

    public function __invoke(
        SentMessageEvent $event,
    ): void {
        // Sendora's id for the message, which the log and
        // the webhooks use.
        $this->logger->info('Sendora took the mail', [
            'message_id' => $event->getMessage()
                ->getMessageId(),
        ]);
    }
}
```

## Webhooks

The parser checks each delivery's signature, and Symfony hands it to the app's consumer of the type `sendora`.

1. Write the consumer, a class with `#[AsRemoteEventConsumer('sendora')]`, such as `src/Webhook/SendoraConsumer.php`. This one logs a bounce, and files each received mail as [Received mail](#received-mail) explains:

```php
<?php

namespace App\Webhook;

use Psr\Log\LoggerInterface;
use Sendora\Sendora;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\RemoteEvent\Attribute\AsRemoteEventConsumer;
use Symfony\Component\RemoteEvent\Consumer\ConsumerInterface;
use Symfony\Component\RemoteEvent\Event\Mailer\MailerDeliveryEvent;
use Symfony\Component\RemoteEvent\RemoteEvent;

#[AsRemoteEventConsumer('sendora')]
final class SendoraConsumer implements ConsumerInterface
{
    public function __construct(
        private readonly Sendora $sendora,
        private readonly LoggerInterface $logger,
        #[Autowire('%kernel.project_dir%/var/tickets')]
        private readonly string $tickets,
    ) {}

    public function consume(RemoteEvent $event): void
    {
        $name = $event->getName();
        if ($event instanceof MailerDeliveryEvent) {
            if ($name === MailerDeliveryEvent::BOUNCE) {
                $this->bounced($event);
            }
        } elseif ($name === 'inbound') {
            $id = $event->getPayload()['inboundMessageId']
                ?? null;
            if (is_string($id)) {
                $this->file($id);
            }
        }
    }

    private function bounced(
        MailerDeliveryEvent $event,
    ): void {
        $this->logger->warning('A message bounced', [
            'message_id' => $event->getId(),
            'reason' => $event->getReason(),
        ]);
    }

    private function file(string $inboundMessageId): void
    {
        $mail = $this->sendora->inbound->get(
            $inboundMessageId,
        );
        // Only a DMARC pass proves who sent it.
        $folder = $mail->authentication->dmarc === 'pass'
            ? $this->tickets
            : "{$this->tickets}/unverified";
        (new Filesystem())->dumpFile(
            "{$folder}/{$inboundMessageId}.txt",
            $mail->text ?? '',
        );
    }
}
```

2. Create a webhook under the server's [Webhooks](https://app.sendora.se/servers) tab, with the address of the route, such as `https://example.se/webhook/sendora`. [Webhooks](https://sendora.se/docs/webhooks#register) shows how to create one through the API.
3. Put its secret in `SENDORA_WEBHOOK_SECRET`, and deploy.

| Event                 | Symfony's event         | `getName()`           |
| --------------------- | ----------------------- | --------------------- |
| `delivered`           | `MailerDeliveryEvent`   | `delivered`           |
| `bounced`             | `MailerDeliveryEvent`   | `bounce`              |
| `deferred`            | `MailerDeliveryEvent`   | `deferred`            |
| `spam_complaint`      | `MailerEngagementEvent` | `spam`                |
| `unsubscribed`        | `MailerEngagementEvent` | `unsubscribe`         |
| `opened`              | `MailerEngagementEvent` | `open`                |
| `clicked`             | `MailerEngagementEvent` | `click`               |
| `tracking_opted_out`  | `RemoteEvent`           | `tracking_opted_out`  |
| `cap_warning`         | `RemoteEvent`           | `cap_warning`         |
| `cap_reached`         | `RemoteEvent`           | `cap_reached`         |
| `inbound`             | `RemoteEvent`           | `inbound`             |
| `inbound_cap_warning` | `RemoteEvent`           | `inbound_cap_warning` |
| `inbound_cap_reached` | `RemoteEvent`           | `inbound_cap_reached` |
| any other             | `RemoteEvent`           | the event's name      |

[Webhooks](https://sendora.se/docs/webhooks#events) says when Sendora sends each event.

- A mailer event's `getId()` is Sendora's message id, the one that `SentMessageEvent` carried. Its `getRecipientEmail()`, `getDate()` and `getMetadata()` give the event's recipient, time and metadata. `getTags()` holds the message's one tag, if it has one.
- A bounce's `getReason()` is the receiving server's response, or else the bounce's classification.
- Every other event's `getId()` is the delivery's id. Every event's `getPayload()` is the delivery as Sendora sent it, with the fields that [Webhook events](https://sendora.se/docs/api/webhook-events) lists.
- A delivery can arrive more than once. Key your handling on the payload's `id`, the delivery's id, which stays the same on each attempt.
- To [roll the secret](https://sendora.se/docs/webhooks#roll-the-secret), create the new one and set `SENDORA_WEBHOOK_SECRET` to it. Sendora signs each delivery with both until you delete the old one.

Symfony hands each event to the consumer through Messenger, which runs the consumer before Symfony answers, unless you route it elsewhere. Symfony then answers 202, or 500 if the consumer throws. Sendora waits only as long as [Limits](https://sendora.se/docs/limits#webhooks) says, and delivers again later after any answer but a 2xx, so keep the consumer quick. To answer at once, route `Symfony\Component\RemoteEvent\Messenger\ConsumeRemoteEventMessage` to an async transport in `config/packages/messenger.yaml`. The consumer then runs in Messenger's worker, which retries it when it throws. A bad or stale signature gets 400.

## Received mail

The consumer above files each received mail. An `inbound` event's payload has the message's `inboundMessageId`, and the client fetches the mail by it.

- An `inbound` event carries the whole mail unless the webhook was created with `inboundContent` set to `reference`, as [Inbound](https://sendora.se/docs/inbound#the-inbound-event) explains. The consumer fetches the mail, so create the webhook that way through the API.
- With the consumer in Messenger's worker, each delivery waits in the transport's store, in clear. A webhook created with `reference` keeps the mail out of it.
- Only a DMARC `pass` proves that the From domain sent the message. With any other verdict, the From address may be forged.
- Sendora keeps the mail's content for the stream's retention, as [Inbound](https://sendora.se/docs/inbound#what-sendora-keeps) says. After that, the consumer finds its `text` null.
- A test server has no inbound stream, so receive mail on a live server.

## Develop against a test server

A test server checks and logs each mail as a live server does, and delivers none of it. Its keys start with `sk_test_`.

1. Create a test server under [Servers › New server](https://app.sendora.se/servers/new), with **Testserver** ticked, and a key on its **API keys** tab.
2. Put the key in `SENDORA_API_TOKEN` in `.env.local` on your machine, and in CI. Keep a live server's key in production.
3. Send to the [simulator's addresses](https://sendora.se/docs/test-servers#the-simulators-addresses), such as `hardbounce@simulator.sendora.se`, to act out a bounce or a complaint. The message's events show in the dashboard's message log, as [Messages and events](https://sendora.se/docs/messages) explains.

Then refuse a test key where mail must arrive, in `src/Kernel.php`:

```php
<?php

namespace App;

use Sendora\Keys;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;

class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    public function boot(): void
    {
        parent::boot();

        // Every place Symfony reads the environment from.
        $token = $_ENV['SENDORA_API_TOKEN']
            ?? $_SERVER['SENDORA_API_TOKEN']
            ?? getenv('SENDORA_API_TOKEN');
        if (
            $this->environment === 'prod'
            && is_string($token)
            && Keys::isTestKey($token)
        ) {
            throw new \RuntimeException(
                'SENDORA_API_TOKEN is a test key; '
                    . 'nothing would be delivered',
            );
        }
    }
}
```

Sendora posts webhooks only to a public HTTPS address, so a test server's events cannot reach your machine. To try the consumer, call its `consume()` in a test with an event of your own, such as `new MailerDeliveryEvent(MailerDeliveryEvent::BOUNCE, $messageId, [])`. Or post a signed delivery to `/webhook/sendora` with the client of Symfony's `WebTestCase`, signed as [Verify the signature](https://sendora.se/docs/webhooks#verify-the-signature) describes.

Symfony reads no `.env.local` in its test environment, and the mailer, the client and the webhook route each fail without their variable. So set both variables for your tests in `.env.test.local`, which git ignores, or in CI's environment. To send no mail at all in tests, set the mailer's DSN to `null://null` under `when@test` in `config/packages/mailer.yaml`.
