# Laravel (Go)

Use the official [Lettermint driver for Laravel for Go](https://github.com/lettermint/lettermint-laravel-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](/guides/send-email-with-go) v3. See [Integrations](/sdks) for other packages.

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

## Requirements

Before you start you need:

- Go 1.27 or newer
- [Laravel for Go](https://laravel.com/go/docs) (`go.laravel.com`) 0.1.1 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 package with `go get`:

```bash
go get github.com/lettermint/lettermint-laravel-go
```

List the package in `bootstrap/app.go`:

```go title="bootstrap/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`:

```dotenv title=".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
```

| Variable | Used by |
| --- | --- |
| `LETTERMINT_PROJECT_TOKEN` | The mailers and the client's `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 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:

```go title="bootstrap/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`:

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

## 3. Send your first email

Send emails with Laravel's `mail` package:

```go
import "go.laravel.com/mail"

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

Or specify the mailer explicitly:

```go
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:

```go
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:

```go
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](/guides/send-email-with-go) for every error type.

## 4. Tags

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

```go
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`:

```go
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](/platform/emails/tags).

## 5. Metadata

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

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

:::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.). Name each mailer and its route in `Config.Mailers`:

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

Send to specific routes:

```go
// 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`:

```go
Options: []mail.TransportOption{lettermint.Options{
	IdempotencyKey: fmt.Sprintf("welcome-%d", 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 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`:

```go
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](/guides/send-email-with-go) 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):

```go
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:

```go
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](/platform/webhooks/signing) 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`:

```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 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](/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 route a path of your own to the package's handler:

```go title="routes/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 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 the `lettermint` package.

### Listening to events

Write a listener for each event you need:

```go title="listeners/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`:

```go title="bootstrap/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:

```go
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:

```go
func LogWebhook(ctx context.Context, e lettermint.WebhookReceived) error {
	slog.InfoContext(ctx, "webhook received", "type", e.Event, "delivery", e.ID)

	return nil
}
```

## FAQ

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

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.

</details>

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

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.

</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 `lettermint.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-go">
    Find the complete source code, report issues, or contribute on GitHub.
</Card>
