# Laravel (Rust)

Use the official [Lettermint driver for Laravel for Rust](https://github.com/lettermint/lettermint-laravel-rust) with Laravel's mail, queued mail, tags, metadata, and idempotency. It also registers one shared Lettermint client for direct API calls, and receives verified webhooks as Laravel events. The driver uses the [Rust SDK](/guides/send-email-with-rust). See [Integrations](/sdks) for other packages.

Using Laravel with PHP or Go? Follow the [Laravel (PHP)](/guides/send-email-with-laravel) or [Laravel (Go)](/guides/send-email-with-laravel-go) guide instead.

## Requirements

Before you start you need:

- Rust 1.99 or newer
- [Laravel for Rust](https://docs.rs/laravel-rust) (`laravel-rust`) 0.1.2 or newer
- A [Lettermint account](https://app.lettermint.co) with a verified sending domain
- A Project API token from your [project settings](https://app.lettermint.co/projects)
- Optional: a Team API token, to manage domains, projects, routes, and messages from your app

If your domain is not verified yet, follow the [domain setup guide](/platform/domains/introduction) first so your mail reaches the inbox instead of the spam folder.

## 1. Installation

Add the crate with Cargo:

```bash
cargo add lettermint-laravel
```

Add the service provider to your application:

```rust title="src/main.rs"
use std::process::ExitCode;

use laravel::Application;
use lettermint_laravel::LettermintServiceProvider;

fn main() -> ExitCode {
    Application::configure()
        .with_providers(|providers| {
            providers.add(LettermintServiceProvider);
        })
        .run()
}
```

The provider reads its configuration from the environment, adds a `lettermint` mailer, registers the Lettermint client, and registers the webhook endpoint.

## 2. Configuration

### Environment variables

Add your Lettermint credentials to `.env`:

```dotenv title=".env"
# Sends email: the mail transport and lettermint.emails()
LETTERMINT_PROJECT_TOKEN=your-lettermint-project-token
# Optional: the Team API (domains, messages, projects, routes, webhooks, ...)
LETTERMINT_TEAM_TOKEN=your-lettermint-team-token
LETTERMINT_ROUTE_ID=your-route-id
```

| Variable | Used by |
| --- | --- |
| `LETTERMINT_PROJECT_TOKEN` | The mail transport and `lettermint.emails()` |
| `LETTERMINT_TEAM_TOKEN` | Every other part of the client |

Configure one token or both. Each part uses its own token and never falls back to the other one. With only a project token you can send email, and a Team API call returns an `Error::Config` that names the missing token before any request is made.

Requests time out after 15 seconds, covering the whole request including reading the response. Change it with `LETTERMINT_TIMEOUT=30` (seconds).

### Changing the configuration in code

The configuration is the `LettermintConfig` section. Change it in your application's config callback, which runs after the provider has read the environment:

```rust
use std::time::Duration;

use laravel::Application;
use lettermint_laravel::{LettermintConfig, LettermintServiceProvider};

Application::configure()
    .with_providers(|providers| {
        providers.add(LettermintServiceProvider);
    })
    .with_config(|config, _| {
        config.section_mut::<LettermintConfig>().timeout = Duration::from_secs(30);
    });
```

### Mail configuration

Set Lettermint as your default mailer in `.env`:

```dotenv title=".env"
MAIL_MAILER=lettermint
```

## 3. Send your first email

Send emails with Laravel's mail functions:

```rust
use laravel::mail::{self, Message};

mail::to("recipient@example.com")
    .send(Message::new().subject("Welcome to Acme").html("<p>Thanks for signing up.</p>"))
    .await?;
```

Or specify the mailer explicitly:

```rust
mail::mailer("lettermint")
    .to("recipient@example.com")
    .send(welcome)
    .await?;
```

### Queued and bulk sending

Because Lettermint is a standard Laravel mail driver, it works with Laravel's queue out of the box. Queue a message so sending happens in the background:

```rust
mail::to("recipient@example.com").queue(welcome).await?;
```

For higher volumes, run more queue workers, exactly as you would with any Laravel mailer.

### Handle errors

When Lettermint rejects an email or cannot be reached, the send returns a `laravel::Error` that holds a `SendError`. `SendError::lettermint_error()` returns the SDK's error, with the HTTP status, the API's error code, and its field errors:

```rust
use lettermint_laravel::{SendError, lettermint};

fn describe(error: &laravel::Error) {
    let Some(error) = error.downcast_ref::<SendError>() else {
        return;
    };

    match error.lettermint_error() {
        lettermint::Error::Validation(error) => eprintln!("{:?}", error.errors()),
        lettermint::Error::RateLimit(error) => eprintln!("retry after {:?}", error.retry_after()),
        other => eprintln!("{other}"),
    }
}
```

A queued email that Lettermint rejects with a 4xx status other than 408, 409, or 429 fails without another attempt, because sending it again can't change the outcome. Rate limits, server errors, timeouts, and connection failures are retried.

See the [Rust SDK guide](/guides/send-email-with-rust) for every error variant.

## 4. Tags

Categorize emails for filtering and analytics in your Lettermint dashboard. Name/value tags use Laravel's `tag` method:

```rust
use laravel::mail::Message;

let message = Message::new()
    .subject("Welcome to Acme")
    .text("Thanks for signing up.")
    .tag("campaign", "onboarding")
    .tag("environment", "production");
```

The single plain tag goes in `Options`:

```rust
use lettermint_laravel::Options;

let message = message.with(Options::new().tag("onboarding"));
```

Tag names have 1 to 32 characters and values 1 to 64 characters, both from `A-Z`, `a-z`, `0-9`, `_`, and `-`. An email can have up to 20 name/value tags, or 19 when it also has a plain tag. The SDK checks these rules before the request is sent. See [Tags documentation](/platform/emails/tags).

## 5. Metadata

Attach custom data for tracking and webhook payloads with `Options`:

```rust
use laravel::mail::Message;
use lettermint_laravel::Options;

let message = Message::new()
    .subject("Order confirmation")
    .html(html)
    .with(
        Options::new()
            .metadata("order_id", order.id.to_string())
            .metadata("customer_id", order.customer_id.to_string()),
    );
```

A message holds one `Options`: adding it again replaces the earlier one. Other transports ignore it.

:::note
Metadata is included in webhook payloads but not sent to recipients.
:::

## 6. Multiple routes

Configure separate mailers for different email types (transactional, marketing, etc.):

```rust
use laravel::Application;
use lettermint_laravel::{LettermintMailer, LettermintServiceProvider};

Application::configure()
    .with_providers(|providers| {
        providers.add(LettermintServiceProvider);
    })
    .with_config(|config, _| {
        config.mail.add_mailer("lettermint_transactional", LettermintMailer::new().route("transactional"));
        config.mail.add_mailer("lettermint_marketing", LettermintMailer::new().route("marketing"));
    });
```

Send to specific routes:

```rust
// Transactional emails (password resets, order confirmations)
mail::mailer("lettermint_transactional").to(user.email.as_str()).send(password_reset).await?;

// Marketing emails (newsletters, promotions)
mail::mailer("lettermint_marketing").to(user.email.as_str()).send(newsletter).await?;
```

To send one email through another route, set it in `Options` with `.route("billing")`.

## 7. Idempotency

Prevent duplicate emails when retrying failed requests.

### Automatic keys

The driver sends the email's ID as its idempotency key, so you configure nothing. Laravel gives each email an ID that stays the same across a queued email's retries, so a retry after a timeout never sends the email twice, and two different emails never share a key.

### Custom idempotency key

Override the automatic key for specific emails with `Options`:

```rust
use lettermint_laravel::Options;

let message = welcome.with(Options::new().idempotency_key(format!("welcome-{}", user.id)));
```

:::tip
Lettermint keeps an idempotency key for 24 hours. Keys are scoped per project; retrying the same payload returns the cached `202 Accepted` response, while reusing a key with a different payload returns `409 Conflict`.
:::

## 8. Use the Lettermint client

The provider registers one `lettermint::Lettermint` client as a singleton, built from your configuration. It holds no message state, so the same instance serves every request and queue worker. Inject it in a handler:

```rust
use laravel::container::Inject;
use lettermint_laravel::lettermint::{Lettermint, SendOptions};

async fn send_invoice(lettermint: Inject<Lettermint>) -> laravel::Result<String> {
    let response = lettermint
        .emails()
        .compose()
        .from("billing@acme.com")
        .to("jane@example.com")
        .subject("Your invoice")
        .html("<p>Your invoice is attached.</p>")
        .send(SendOptions::new().idempotency_key("invoice-1234"))
        .await?;

    Ok(response.message_id)
}
```

Or resolve it anywhere with `lettermint_laravel::client().await?`. The crate re-exports the SDK as `lettermint_laravel::lettermint`. The [Rust guide](/guides/send-email-with-rust) covers the email builder, batch sending, scheduling, pagination, and response types.

### Team API

With `LETTERMINT_TEAM_TOKEN` configured, the same client reaches the [Team API](/platform/teams/team-api/quickstart):

```rust
use lettermint_laravel::lettermint::types::{DomainStatus, ListDomainsQuery};

let lettermint = lettermint_laravel::client().await?;

let domains = lettermint
    .domains()
    .list(&ListDomainsQuery { filter_status: Some(DomainStatus::Verified), ..Default::default() })
    .await?;

let team = lettermint.team().retrieve(&Default::default()).await?;
```

### Laravel's HTTP client

The client sends its requests with Laravel's HTTP client, with redirects and transport retries turned off. Its hooks and tracing see every request, and `laravel::http::client::fake()` fakes them in tests:

```rust
use laravel::http::client;
use laravel::mail::{self, Message};
use serde_json::json;

#[laravel::test(app = application)]
async fn sends_the_welcome_email() {
    let http = client::fake()
        .prevent_stray_requests()
        .with("https://api.lettermint.co/v1/send", json!({ "message_id": "msg_123", "status": "pending" }));

    mail::to("jane@example.com").send(Message::new().subject("Welcome").text("Hi")).await.unwrap();

    http.assert_sent(|request| request.json::<serde_json::Value>().unwrap()["subject"] == "Welcome");
}
```

## 9. Webhooks

The driver receives Lettermint webhooks, [verifies their signature](/platform/webhooks/signing) with the Rust SDK, and dispatches a Laravel event for each delivery.

### Configuration

Add the webhook's signing secret, including its `whsec_` prefix, to `.env`:

```dotenv title=".env"
LETTERMINT_WEBHOOK_SECRET=whsec_...
LETTERMINT_WEBHOOK_PREFIX=lettermint
LETTERMINT_WEBHOOK_TOLERANCE=300
```

The prefix and the timestamp tolerance (in seconds) are optional. The provider registers the endpoint `POST /{prefix}/webhook`, without a middleware group. By default that is `POST /lettermint/webhook`. Add its URL to the webhook in your [Lettermint dashboard](/platform/webhooks/introduction).

### Verification

Every request must carry the `X-Lettermint-Signature` and `X-Lettermint-Delivery` headers that Lettermint sends, and the raw body exactly as it was sent. If a proxy or load balancer sits in front of your application, make sure it forwards both headers and does not change the body.

A request that fails verification gets a `401` response whose `reason` says why, for example `signature_mismatch` or `timestamp_out_of_tolerance`, and no event is dispatched. A verified delivery is acknowledged with `200`.

### Custom webhook routes

To register the endpoint yourself, disable the automatic route:

```dotenv title=".env"
LETTERMINT_WEBHOOK_ENABLED=false
```

Then register the handler in your routing:

```rust
use laravel::Application;
use lettermint_laravel::LettermintServiceProvider;

Application::configure()
    .with_providers(|providers| {
        providers.add(LettermintServiceProvider);
    })
    .with_routing(|routing, _| {
        routing.routes(|route| {
            route.post("/hooks/lettermint", lettermint_laravel::webhooks::handle);
        });
    });
```

Register it with `routing.routes(..)` or `routing.api(..)`, not `routing.web(..)`, because the `web` group's CSRF check rejects Lettermint's request. In a handler of your own, `lettermint_laravel::webhooks::verify(&headers, &body)` returns the verified `WebhookPayload`, and `lettermint_laravel::events::dispatch(payload)` dispatches its events.

### Available events

| Event type | Webhook type | Description |
| --- | --- | --- |
| `MessageCreated` | `message.created` | Message accepted for processing |
| `MessageSent` | `message.sent` | Message sent to the recipient's server |
| `MessageDelivered` | `message.delivered` | Message delivered |
| `MessageHardBounced` | `message.hard_bounced` | Permanent delivery failure |
| `MessageSoftBounced` | `message.soft_bounced` | Temporary delivery failure |
| `MessageSpamComplaint` | `message.spam_complaint` | Recipient reported spam |
| `MessageFailed` | `message.failed` | Processing failure |
| `MessageSuppressed` | `message.suppressed` | Message suppressed |
| `MessagePolicyRejected` | `message.policy_rejected` | Rejected by the sending policy |
| `MessageUnsubscribed` | `message.unsubscribed` | Recipient unsubscribed |
| `MessageOpened` | `message.opened` | Recipient opened the email |
| `MessageClicked` | `message.clicked` | Recipient clicked a link |
| `MessageInbound` | `message.inbound` | Inbound email received |
| `InboundRejected` | `inbound.rejected` | Inbound email rejected during SMTP |
| `MessageAutoReplied` | `message.auto_replied` | An automatic reply was received |
| `MessageScheduled` | `message.scheduled` | A message was scheduled |
| `MessageRescheduled` | `message.rescheduled` | A message's schedule changed |
| `MessageCanceled` | `message.canceled` | A scheduled message was canceled |
| `MessageReleased` | `message.released` | A scheduled message was released |
| `SuppressionAdded` | `suppression.added` | Suppression entry added |
| `SuppressionRemoved` | `suppression.removed` | Suppression entry removed |
| `WebhookTest` | `webhook.test` | Test event from the dashboard |

All event types are in `lettermint_laravel::events`.

### Listening to events

Listen to the events you need:

```rust
use laravel::Application;
use laravel::event::Event;
use lettermint_laravel::events::{MessageDelivered, MessageHardBounced, WebhookEvent};
use serde::Deserialize;

#[derive(Deserialize)]
struct Bounce {
    message_id: String,
    recipient: String,
}

async fn log_delivery(event: Event<MessageDelivered>) {
    tracing::info!(message_id = %event.payload.data["message_id"], "Email delivered");
}

async fn disable_recipient(event: Event<MessageHardBounced>) -> laravel::Result<()> {
    // A permanent bounce: consider disabling the recipient.
    let bounce: Bounce = event.data_as()?;
    tracing::warn!(message_id = %bounce.message_id, recipient = %bounce.recipient, "Hard bounce");
    Ok(())
}

Application::configure().with_events(|events, _| {
    events.listen(log_delivery);
    events.listen(disable_recipient);
});
```

Listeners in your `app` crate marked `#[listener]` are discovered automatically, so you register nothing. Do not register a discovered listener again by hand, or it runs twice.

The endpoint answers `200` once every listener has run. When a listener returns an error, the endpoint answers `500`, and Lettermint delivers the webhook again later.

### Event structure

Each typed event has one field, `payload`, the verified `lettermint::WebhookPayload`:

```rust
event.payload.id;             // Option<String>, the delivery ID
event.payload.event;          // "message.delivered"
event.payload.timestamp;      // Option<String>, ISO 8601
event.payload.data;           // serde_json::Value: data["message_id"], data["recipient"], ...
event.payload.extra["context"]; // The payload's other fields
```

The `WebhookEvent` trait gives every typed event `data_as::<T>()`, which decodes `data` into a type of your own, and `event_type()`.

### Unknown event types

When Lettermint sends an event type that your version of the crate does not know yet, the delivery is still acknowledged with a `200` response, and an `UnknownWebhookEventReceived` event is dispatched with the event name and the verified payload. Update the crate to receive a typed event instead.

### Listening to all events

After its typed event (or `UnknownWebhookEventReceived`), every delivery also dispatches `WebhookReceived`, so one listener receives all of them:

```rust
use laravel::event::Event;
use lettermint_laravel::events::WebhookReceived;

async fn log_webhook(event: Event<WebhookReceived>) {
    tracing::info!(r#type = event.payload.event.as_str(), id = ?event.payload.id, "Webhook received");
}
```

## FAQ

<details>
<summary>Which Laravel for Rust and Rust versions are supported?</summary>

Rust 1.99 or newer and Laravel for Rust 0.1.2 or newer. The crate is tested on Linux, macOS, and Windows, on Rust 1.99 and the latest stable release.

</details>

<details>
<summary>Do messages and queued mail work as usual?</summary>

Yes. Lettermint registers as a standard mail driver, so everything you already build with `mail::to`, `Message`, and the queue keeps working. Only the delivery happens through Lettermint.

</details>

<details>
<summary>How do I prevent duplicate emails?</summary>

You don't need to do anything. The driver sends the email's ID as the idempotency key, and that ID stays the same when a queue worker tries the email again. Override the key per message with `Options`, as shown in the idempotency section above.

</details>

<details>
<summary>How do I track deliveries and bounces?</summary>

The driver verifies Lettermint's webhooks and dispatches Laravel events such as `MessageDelivered` and `MessageHardBounced`, so you can react in your app. For opens and clicks, enable [tracking](/platform/emails/tracking/introduction) on the route your mailer uses.

</details>

<details>
<summary>Is Lettermint email GDPR compliant and EU-hosted?</summary>

Yes. Lettermint runs exclusively on European infrastructure and processes email in line with GDPR, so transactional mail from your Laravel app is handled inside the EU.

</details>

## Next steps

<CardGroup cols={2}>
    <Card title="Tags" icon="tag" href="/platform/emails/tags">
        Organize and filter emails with tags.
    </Card>
    <Card title="Tracking" icon="chart-line" href="/platform/emails/tracking/introduction">
        Track opens, clicks, and deliverability.
    </Card>
    <Card title="Webhooks" icon="webhook" href="/platform/webhooks/introduction">
        Receive delivery events through webhooks.
    </Card>
    <Card title="SMTP Alternative" icon="envelope" href="/guides/send-email-with-smtp">
        Send via SMTP instead of the API.
    </Card>
</CardGroup>

<Card title="GitHub Repository" icon="github" href="https://github.com/lettermint/lettermint-laravel-rust">
    Find the complete source code, report issues, or contribute on GitHub.
</Card>
