# Laravel

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

The Laravel package, `sendora/sendora-laravel`, sends a Laravel app's mail through the API. Its route checks each webhook's signature and fires a Laravel event, and its clients reach the rest of the API. It runs on Laravel 12 with PHP 8.2 or newer, and on Laravel 13 with PHP 8.3 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-laravel
```

Laravel finds the package by itself. The package installs the PHP SDK, `sendora/sendora-php`, which its clients build on.

## Settings

Set the key, the mailer, the sender and the webhook's secret in `.env`:

```bash
SENDORA_API_TOKEN=sk_…
MAIL_MAILER=sendora
MAIL_FROM_ADDRESS=no-reply@example.se
MAIL_FROM_NAME="Example AB"
SENDORA_WEBHOOK_SECRET=whsec_…
```

- `SENDORA_API_TOKEN` is the server key. It sends Laravel's mail, and every call through the package's facade.
- `MAIL_MAILER=sendora` sends every mailable and every mail notification through the API. `config/mail.php` needs no entry for it.
- `MAIL_FROM_ADDRESS` and `MAIL_FROM_NAME` are the sender. The address must be on a verified domain, and a mailable may set its own.
- `SENDORA_WEBHOOK_SECRET` is the webhook's signing secret, which you get once you create the webhook, as [Webhooks](#webhooks) below shows. The route for webhooks exists only once it is set.

To send on a [stream](https://sendora.se/docs/streams) other than the server's default, set `SENDORA_STREAM` to its id. If the app caches its config, run `php artisan config:cache` again after each change. The other settings, such as the timeout and the route's path, are in the package's settings file. Publish it with `php artisan vendor:publish --tag=sendora-config` to change them.

## Send mail

Send with Laravel's own mailables and notifications. A mailable's envelope sets the message's tag and metadata in Sendora:

```php
<?php

namespace App\Mail;

use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;

final class OrderShipped extends Mailable
{
    public function __construct(
        public readonly string $orderId,
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Your order has shipped',
            // The message's tag and metadata in Sendora.
            tags: ['order-shipped'],
            metadata: ['order_id' => $this->orderId],
        );
    }

    public function content(): Content
    {
        return new Content(
            markdown: 'mail.order-shipped',
        );
    }
}
```

`php artisan make:mail OrderShipped --markdown=mail.order-shipped` makes the class and its view. Send the mail as you send any mailable:

```php
<?php

use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;

$sent = Mail::to('anna@example.com')
    ->send(new OrderShipped('1042'));

// Sendora's id for the message, which the log and the
// webhooks use.
$messageId = $sent?->getMessageId();
```

- `send()` returns the sent message, and its `getMessageId()` is Sendora's id for the message. `send()` returns null for a mailable that is queued. Laravel's `MessageSent` event then carries the id, as `$event->sent->getMessageId()`.
- A message has one tag. Two different tags fail the send before anything goes out.
- Attachments, Cc, Bcc and Reply-To go through as Laravel sets them.
- When the queue retries a job, a mail that went out on an earlier attempt is not sent again. The package sends each mail of a job under an [idempotency key](https://sendora.se/docs/sending#idempotency) made from the job's id.
- A mail that comes out different on the retry, as a signed URL's new expiry makes it, goes again. To send such a mail once, set the header `X-Sendora-Idempotency-Key` in the mailable's `headers()` from an id of your own, such as the order's. A retry that comes out different then fails with `idempotency_key_mismatch`, and sends nothing.
- A failed send throws Symfony's `TransportException`, whose previous exception is the SDK's.

For the rest of the API, the facade `Sendora\Laravel\Facades\Sendora` reaches the server's resources, as in `Sendora::messages()->get($messageId)`. A class may take a resource from the container instead, such as `Sendora\Resources\Messages`.

## Webhooks

The package's route takes each delivery, checks its signature and fires a Laravel event for it. A delivery is one post of one event to your webhook.

1. Listen for the events you want, as you listen for any Laravel event. In a class in `app/Listeners`, Laravel registers each method whose name starts with `handle` for the event its argument names. `Event::listen()` registers a listener in a provider instead.

```php
<?php

namespace App\Listeners;

use Illuminate\Support\Facades\Log;
use Sendora\Laravel\Events\MessageBounced;
use Sendora\Laravel\Events\MessageDelivered;

// Laravel finds each method that starts with "handle"
// and registers it for the event its argument names.
final class TrackDeliveries
{
    public function handleDelivered(
        MessageDelivered $event,
    ): void {
        Log::info('Sendora delivered a message', [
            'message_id' => $event->webhook->messageId,
        ]);
    }

    public function handleBounced(
        MessageBounced $event,
    ): void {
        $bounce = $event->webhook;
        if (!$bounce->details->hard) {
            return;
        }
        Log::warning('A message bounced for good', [
            'message_id' => $bounce->messageId,
            'reason' => $bounce->details->classification,
        ]);
    }
}
```

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/sendora/webhook`. [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. If the app caches its routes, run `php artisan route:cache` again.

The route is `POST /sendora/webhook`, named `sendora.webhook`. It sits outside the `web` middleware group, so Laravel's CSRF check never applies to it.

| Event                 | Laravel event in `Sendora\Laravel\Events` |
| --------------------- | ----------------------------------------- |
| `delivered`           | `MessageDelivered`                        |
| `bounced`             | `MessageBounced`                          |
| `deferred`            | `MessageDeferred`                         |
| `spam_complaint`      | `SpamComplaintReceived`                   |
| `unsubscribed`        | `RecipientUnsubscribed`                   |
| `opened`              | `MessageOpened`                           |
| `clicked`             | `LinkClicked`                             |
| `tracking_opted_out`  | `RecipientOptedOut`                       |
| `cap_warning`         | `CapWarning`                              |
| `cap_reached`         | `CapReached`                              |
| `inbound`             | `InboundEmailReceived`                    |
| `inbound_cap_warning` | `InboundCapWarning`                       |
| `inbound_cap_reached` | `InboundCapReached`                       |
| any other             | `UnknownWebhookReceived`                  |

[Webhooks](https://sendora.se/docs/webhooks#events) says when Sendora sends each event. Each Laravel event holds Sendora's event in `$event->webhook`, with the fields that [Webhook events](https://sendora.se/docs/api/webhook-events) lists. Every Laravel event implements `WebhookReceived`, so a listener of that interface hears them all.

- The route answers 204 once the listeners that are not queued have run. Sendora waits only as long as [Limits](https://sendora.se/docs/limits#webhooks) says, so queue slow work.
- A listener that throws stops the listeners after it, and makes the answer 500. Sendora then delivers the event again later, on the schedule that [Webhooks](https://sendora.se/docs/webhooks#retries-dead-letters-and-replay) gives.
- A queued listener runs in the queue's worker, so Sendora never sees it fail. The queue retries it as often as its `$tries` allows.
- A delivery can arrive more than once. Key your handling on `$event->webhook->id`, the delivery's id, which stays the same on each attempt.
- A bad or stale signature gets 400 and fires nothing.
- 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. A comma separates several secrets, for several webhooks that share the route.

## Received mail

`InboundEmailReceived` fires for each message that arrives on the server's [inbound stream](https://sendora.se/docs/inbound). A queued listener would put the whole mail in the queue's store, in clear. So queue a job with the message's id alone:

```php
<?php

namespace App\Listeners;

use App\Jobs\FileTheTicket;
use Sendora\Laravel\Events\InboundEmailReceived;

final class QueueTheTicket
{
    public function handle(
        InboundEmailReceived $event,
    ): void {
        // The id alone, so that the queue never holds the
        // mail itself.
        FileTheTicket::dispatch(
            $event->webhook->inboundMessageId,
        );
    }
}
```

Then fetch the mail in the job:

```php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
use Sendora\Resources\Inbound;

final class FileTheTicket implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public readonly string $inboundMessageId,
    ) {}

    public function handle(Inbound $inbound): void
    {
        $mail = $inbound->get($this->inboundMessageId);

        // Only a DMARC pass proves who sent it.
        $folder = $mail->authentication->dmarc === 'pass'
            ? 'tickets'
            : 'tickets/unverified';
        Storage::put(
            "{$folder}/{$this->inboundMessageId}.txt",
            $mail->text ?? '',
        );
    }
}
```

- 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 job fetches the mail, so create the webhook that way through the API.
- 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 job 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 your machine's `.env`, 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 `app/Providers/AppServiceProvider.php`:

```php
<?php

namespace App\Providers;

use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
use Sendora\Keys;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $token = config('sendora.token');
        if (
            App::isProduction()
            && 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. Post a signed delivery in a feature test instead, signed as [Verify the signature](https://sendora.se/docs/webhooks#verify-the-signature) describes. Set the secret in `phpunit.xml` first, as `<env name="SENDORA_WEBHOOK_SECRET" value="whsec_test"/>`, so that the route exists when the app boots:

```php
<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Str;
use Sendora\Laravel\Events\MessageBounced;
use Tests\TestCase;

class BounceWebhookTest extends TestCase
{
    public function test_a_bounce_reaches_the_app(): void
    {
        Event::fake([MessageBounced::class]);
        $body = (string) json_encode([
            'id' => (string) Str::uuid(),
            'attempt' => 1,
            'event' => 'bounced',
            'messageId' => (string) Str::uuid(),
            'recipient' => 'anna@example.com',
            'occurredAt' => '2026-09-15T12:00:03.000Z',
            'serverId' => (string) Str::uuid(),
            'streamId' => (string) Str::uuid(),
            'broadcastId' => null,
            'tag' => 'order-shipped',
            'metadata' => ['order_id' => '1042'],
            'test' => true,
            'details' => [
                'code' => 550,
                'response' => '5.1.1 No such user',
                'classification' => 'InvalidRecipient',
                'hard' => true,
                'expired' => false,
            ],
        ]);
        // Signed as Sendora signs, with the secret that
        // phpunit.xml sets.
        $at = now()->getTimestamp();
        $signature = "t={$at},v1=" . hash_hmac(
            'sha256',
            "{$at}.{$body}",
            'whsec_test',
        );

        $this->call(
            'POST',
            route('sendora.webhook'),
            server: [
                'HTTP_SENDORA_SIGNATURE' => $signature,
            ],
            content: $body,
        )->assertNoContent();

        Event::assertDispatched(
            MessageBounced::class,
            fn(MessageBounced $event): bool
                => $event->webhook->details->hard,
        );
    }
}
```

`Event::fake()` keeps the listeners from running, so this test checks that the route fires the event. Leave the event unfaked to run your listener too. `Mail::fake()` works as usual, and Laravel's own `phpunit.xml` sends mail to the `array` mailer, so the tests send nothing unless you change it.

## For coding agents

Laravel Boost gives a coding agent the rules of each package an app installs. The package ships its rules for Boost, so that an agent sets up Sendora as this guide does. They are two files in `vendor/sendora/sendora-laravel`:

- `resources/boost/guidelines/core.blade.php`, the rules in short, which Boost adds to the agent's instructions, such as `CLAUDE.md` or `AGENTS.md`.
- `resources/boost/skills/sendora/SKILL.md`, the skill `sendora`, which the agent reads for anything beyond those rules.

Run `php artisan boost:install`, and choose `sendora/sendora-laravel` among the third-party packages. After you upgrade the package, `php artisan boost:update` brings in its new rules.
