Frameworks

Laravel (Rust)

Use the official Lettermint driver for Laravel for 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. See Integrations for other packages.

Using Laravel with PHP or Go? Follow the Laravel (PHP) or Laravel (Go) guide instead.

Requirements

Before you start you need:

  • Rust 1.99 or newer
  • Laravel for Rust (laravel-rust) 0.1.2 or newer
  • A Lettermint account with a verified sending domain
  • A Project API token from your project settings
  • 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 first so your mail reaches the inbox instead of the spam folder.

1. Installation

Add the crate with Cargo:

TerminalCode
cargo add lettermint-laravel

Add the service provider to your application:

Rustsrc/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:

.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
VariableUsed by
LETTERMINT_PROJECT_TOKENThe mail transport and lettermint.emails()
LETTERMINT_TEAM_TOKENEvery 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:

RustCode
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:

.env
MAIL_MAILER=lettermint

3. Send your first email

Send emails with Laravel's mail functions:

RustCode
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:

RustCode
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:

RustCode
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:

RustCode
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 for every error variant.

4. Tags

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

RustCode
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:

RustCode
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.

5. Metadata

Attach custom data for tracking and webhook payloads with Options:

RustCode
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.

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

6. Multiple routes

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

RustCode
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:

RustCode
// 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:

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

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:

RustCode
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 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:

RustCode
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:

RustCode
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 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:

.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.

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:

.env
LETTERMINT_WEBHOOK_ENABLED=false

Then register the handler in your routing:

RustCode
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 typeWebhook typeDescription
MessageCreatedmessage.createdMessage accepted for processing
MessageSentmessage.sentMessage sent to the recipient's server
MessageDeliveredmessage.deliveredMessage delivered
MessageHardBouncedmessage.hard_bouncedPermanent delivery failure
MessageSoftBouncedmessage.soft_bouncedTemporary delivery failure
MessageSpamComplaintmessage.spam_complaintRecipient reported spam
MessageFailedmessage.failedProcessing failure
MessageSuppressedmessage.suppressedMessage suppressed
MessagePolicyRejectedmessage.policy_rejectedRejected by the sending policy
MessageUnsubscribedmessage.unsubscribedRecipient unsubscribed
MessageOpenedmessage.openedRecipient opened the email
MessageClickedmessage.clickedRecipient clicked a link
MessageInboundmessage.inboundInbound email received
InboundRejectedinbound.rejectedInbound email rejected during SMTP
MessageAutoRepliedmessage.auto_repliedAn automatic reply was received
MessageScheduledmessage.scheduledA message was scheduled
MessageRescheduledmessage.rescheduledA message's schedule changed
MessageCanceledmessage.canceledA scheduled message was canceled
MessageReleasedmessage.releasedA scheduled message was released
SuppressionAddedsuppression.addedSuppression entry added
SuppressionRemovedsuppression.removedSuppression entry removed
WebhookTestwebhook.testTest event from the dashboard

All event types are in lettermint_laravel::events.

Listening to events

Listen to the events you need:

RustCode
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:

RustCode
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:

RustCode
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

Which Laravel for Rust and Rust versions are supported?

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.

Do messages and queued mail work as usual?

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.

How do I prevent duplicate emails?

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.

How do I track deliveries and bounces?

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 on the route your mailer uses.

Is Lettermint email GDPR compliant and EU-hosted?

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.

Next steps

Tags

Organize and filter emails with tags.

Tracking

Track opens, clicks, and deliverability.

Webhooks

Receive delivery events through webhooks.

SMTP Alternative

Send via SMTP instead of the API.

GitHub Repository

Find the complete source code, report issues, or contribute on GitHub.