Frameworks

Laravel (Go)

Use the official Lettermint driver for Laravel for Go with mailables, 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 Go SDK v3. See Integrations for other packages.

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

Requirements

Before you start you need:

  • Go 1.27 or newer
  • Laravel for Go (go.laravel.com) 0.1.1 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 package with go get:

TerminalCode
go get github.com/lettermint/lettermint-laravel-go

List the package in bootstrap/app.go:

Gobootstrap/app.go
package bootstrap import ( lettermint "github.com/lettermint/lettermint-laravel-go" laravel "go.laravel.com" ) func Options() laravel.Options { return laravel.Options{ Packages: []laravel.Package{lettermint.New()}, // ... } }

The package reads its settings from the environment, adds a lettermint mailer, registers the Lettermint client, and adds the webhook endpoint.

2. Configuration

Environment variables

Add your Lettermint credentials to .env:

.env
# Sends email: the lettermint mailer and the client's 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 mailers and the client's 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 a *lettermint.ConfigError from the SDK that names the missing token before any request is made.

A token that can't be sent in a header, or a LETTERMINT_BASE_URL that isn't a URL, stops the application from starting, so you find out when you deploy.

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

lettermint.New takes functions that change the settings after the package has read the environment:

Gobootstrap/app.go
Packages: []laravel.Package{ lettermint.New(func(cfg *lettermint.Config) { cfg.Timeout = 30 * time.Second }), },

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

GoCode
import "go.laravel.com/mail" err := mail.To(user).Send(r, mails.Welcome{User: user})

Or specify the mailer explicitly:

GoCode
err := mail.Use("lettermint").To(user).Send(r, mails.Welcome{User: user})

Queued and bulk sending

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

GoCode
err := mail.To(user).Queue(r, mails.Welcome{User: user})

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

Handle errors

When Lettermint rejects an email, the send returns a *mail.RejectedError that wraps the SDK's error, so errors.AsType finds both. The SDK's error has the HTTP status, the API's error code, and its field errors:

GoCode
import ( "errors" sdk "github.com/lettermint/lettermint-go/v3" "go.laravel.com/mail" ) err := mail.To(user).Send(r, mails.Welcome{User: user}) if validation, ok := errors.AsType[*sdk.ValidationError](err); ok { r.Report(err) // validation.Errors holds the field errors } else if rejected, ok := errors.AsType[*mail.RejectedError](err); ok { // Lettermint answered with rejected.Status. }

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. So does an email the SDK refuses before sending it, such as one with an invalid tag. Rate limits, server errors, timeouts, and connection failures are retried.

This package is named lettermint too, so import the SDK under another name, such as sdk. See the Go SDK guide for every error type.

4. Tags

Categorize emails for filtering and analytics in your Lettermint dashboard. Name/value tags use the message's Tags:

GoCode
mail.Message{ Subject: "Welcome to Acme", View: "mails.welcome", Tags: map[string]string{"campaign": "onboarding", "environment": "production"}, }

The single plain tag goes in lettermint.Options:

GoCode
Options: []mail.TransportOption{lettermint.Options{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 lettermint.Options:

GoCode
mail.Message{ Subject: "Order confirmation", View: "mails.order", Data: order, Options: []mail.TransportOption{lettermint.Options{ Metadata: map[string]string{ "order_id": strconv.FormatInt(order.ID, 10), "customer_id": strconv.FormatInt(order.CustomerID, 10), }, }}, }

Other mailers ignore lettermint.Options.

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

6. Multiple routes

Configure separate mailers for different email types (transactional, marketing, etc.). Name each mailer and its route in Config.Mailers:

Gobootstrap/app.go
lettermint.New(func(cfg *lettermint.Config) { cfg.Mailers = map[string]string{ "lettermint_transactional": "transactional", "lettermint_marketing": "marketing", } })

Send to specific routes:

GoCode
// Transactional emails (password resets, order confirmations) err := mail.Use("lettermint_transactional").To(user).Send(r, mails.PasswordReset{}) // Marketing emails (newsletters, promotions) err = mail.Use("lettermint_marketing").To(user).Queue(r, mails.Newsletter{})

To send one email through another route, set Route in lettermint.Options.

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 lettermint.Options:

GoCode
Options: []mail.TransportOption{lettermint.Options{ IdempotencyKey: fmt.Sprintf("welcome-%d", 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 package builds one *lettermint.Client from your settings. It holds no message state, so the same client serves every request and queue worker. Get it with lettermint.Client, from a context that carries your application, such as a handler's r or a job's ctx:

GoCode
import ( lettermint "github.com/lettermint/lettermint-laravel-go" sdk "github.com/lettermint/lettermint-go/v3" "go.laravel.com/web" ) func SendInvoice(r *web.Request) *web.Response { client, err := lettermint.Client(r) if err != nil { return web.Fail(err) } sent, err := client.Emails.Compose(). From("billing@acme.com"). To("jane@example.com"). Subject("Your invoice"). HTML("<p>Your invoice is attached.</p>"). Send(r, sdk.WithIdempotencyKey("invoice-1234")) if err != nil { return web.Fail(err) } return web.JSON(map[string]string{"message_id": sent.MessageID}) }

lettermint.Client returns an error when neither token is set. The Go 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:

GoCode
client, err := lettermint.Client(r) if err != nil { return web.Fail(err) } domains, err := client.Domains.List(r, nil) for message, err := range client.Messages.Iterate(r, nil) { // Follows the cursor through every page. } team, err := client.Team.Retrieve(r, nil)

Laravel's HTTP client

The client sends its requests with Laravel's HTTP client from the context you pass it. The SDK keeps its own timeout and doesn't follow redirects. Its requests show in your traces and logs, and httpclienttest fakes them in tests:

GoCode
func TestSendsTheWelcomeEmail(t *testing.T) { client := tests.New(t, laraveltest.Env(map[string]string{ "MAIL_MAILER": "lettermint", "LETTERMINT_PROJECT_TOKEN": "lm_test", })) http := httpclienttest.New(client). PreventStrayRequests(). Respond("https://api.lettermint.co/v1/send", httpclienttest.JSON(map[string]any{"message_id": "msg_123", "status": "pending"})) if err := mail.To(mail.Addr("jane@example.com")).Send(client.Context(), mails.Welcome{}); err != nil { t.Fatal(err) } http.AssertSent(func(req *httpclienttest.Request) bool { return req.Data()["subject"] == "Welcome" }) }

Pass the client a context that carries your application. Like Laravel's own helpers, it panics on one that doesn't.

9. Webhooks

The driver receives Lettermint webhooks, verifies their signature with the Go 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 package adds the endpoint POST /{prefix}/webhook, named lettermint.webhook, as a bare route without the web group's session and CSRF middleware. 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 route a path of your own to the package's handler:

Goroutes/api.go
route.Post("/hooks/lettermint", func(r *web.Request) *web.Response { return lettermint.From(r).HandleWebhook(r) })

Add the route to a group without CSRF protection, such as the API group, so Laravel does not reject Lettermint's request. In a handler of your own, lettermint.From(r).Verify(r) returns the verified payload, and lettermint.Dispatch(r, *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 the lettermint package.

Listening to events

Write a listener for each event you need:

Golisteners/lettermint.go
package listeners import ( "context" "log/slog" lettermint "github.com/lettermint/lettermint-laravel-go" ) func LogDelivery(ctx context.Context, e lettermint.MessageDelivered) error { slog.InfoContext(ctx, "email delivered", "delivery", e.ID) return nil } func DisableRecipient(ctx context.Context, e lettermint.MessageHardBounced) error { // A permanent bounce: consider disabling the recipient. var bounce struct { MessageID string `json:"message_id"` Recipient string `json:"recipient"` } if err := e.DecodeData(&bounce); err != nil { return err } slog.WarnContext(ctx, "hard bounce", "message_id", bounce.MessageID, "recipient", bounce.Recipient) return nil }

Register them in bootstrap/app.go:

Gobootstrap/app.go
Listeners: []laravel.Listener{ laravel.Listen(listeners.LogDelivery), laravel.Listen(listeners.DisableRecipient), },

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 event embeds the verified WebhookPayload from the SDK:

GoCode
e.ID // The delivery ID e.Event // "message.delivered" e.Timestamp // ISO 8601 e.Data // The event's data as raw JSON: decode it with e.DecodeData(&v) e.Raw // The verified request body

Unknown event types

When Lettermint sends an event type that your version of the package does not know yet, the delivery is still acknowledged with a 200 response, and an UnknownWebhookEventReceived event is dispatched with the verified payload, whose Event names the type. Update the package 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:

GoCode
func LogWebhook(ctx context.Context, e lettermint.WebhookReceived) error { slog.InfoContext(ctx, "webhook received", "type", e.Event, "delivery", e.ID) return nil }

FAQ

Which Laravel for Go and Go versions are supported?

Go 1.27 or newer and Laravel for Go 0.1.1 or newer. The package is tested on Linux, macOS, and Windows, on Go 1.27 and the latest stable release.

Do mailables and queued mail work as usual?

Yes. Lettermint registers as a standard mailer, so everything you already build with mail.To, mailables, 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 lettermint.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.