# Go SDK

Install the Mailset Go SDK, send email, verify webhooks and handle errors, with examples that run.

- **Every public command**: 238 commands, each a typed method
- **No dependencies**: Nothing else to install beside it
- **Typed throughout**: Structs and typed enums, checked by vet
- **Retries built in**: Two more tries, and a send never doubles
- **Timeouts per try**: 30 seconds a try, then tried again
- **Idempotency keys**: A send repeated with its key goes once

## Requirements

- Go 1.22 or later

## Install

go get:

```bash
go get mailset.app/go@v0.7.0
```

## Create a client

One client holds one `MAILSET_KEY`. Make it when your server starts and use it for every call.

### Example

```go
import (
	"log"

	mailset "mailset.app/go"
)

// One client for the whole server.
client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
// Nothing is sent until you call a method, and it
// prints the kind of credential, never its value.
log.Println(client)
```

### Pass the key in

Where your app keeps its secrets elsewhere, hand the key to the client yourself. A token goes the same way.

```go
import (
	"log"

	mailset "mailset.app/go"
)

// From your secret store or config, never in the code.
// Or WithToken(cfg.MailsetToken) with an API token.
client, err := mailset.NewClient(
	mailset.WithKey(cfg.MailsetKey),
)
if err != nil {
	log.Fatal(err)
}
```

### Options

Everything has a default. Name a credential, an org, how long a try may take and how often a call is tried again, only where yours differ.

```go
import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	mailset "mailset.app/go"
)

// A command that needs a passkey waits for
// someone to approve it.
onApproval := func(
	ctx context.Context, approval *mailset.Approval,
) error {
	fmt.Println("Approve it:", approval.URL)
	return nil
}

client, err := mailset.NewClient(
	// Or WithToken(os.Getenv("MAILSET_TOKEN")).
	mailset.WithKey(os.Getenv("MAILSET_KEY")),
	// The org commands are about, for a person
	// in more than one.
	mailset.WithOrg("org_7c2e9a4f"),
	// Each try may take 10 seconds, and a network
	// failure or a 5xx is tried 3 more times,
	// waiting longer each time.
	mailset.WithTimeout(10*time.Second),
	mailset.WithMaxRetries(3),
	mailset.WithOnApproval(onApproval),
)
if err != nil {
	log.Fatal(err)
}

ctx := context.Background()
status, err := client.Key.Check(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(status.Name)
```

More: [Authentication](https://mailset.app/docs/authentication)

## Send

Send one message and get its receipt. A message Mailset refuses is an error with a code, never a silent drop.

### Example

```go
import (
	"context"
	"fmt"
	"log"
	"time"

	mailset "mailset.app/go"
)

client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

sent, err := client.Send(ctx, mailset.Message{
	From:      "Acme <hello@example.com>",
	To:        []string{"ana@example.org"},
	Subject:   "Your Acme code",
	Text:      "Your code is 123456.",
	HTML:      "<p>Your code is <b>123456</b>.</p>",
	DeliverBy: mailset.Within(10 * time.Minute),
})
if err != nil {
	log.Fatal(err)
}

fmt.Println(sent.ID, sent.Status)
```

More: [Give sign-in codes a deadline](https://mailset.app/docs/recipes/deadlines), [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes), [Handle skipped recipients](https://mailset.app/docs/recipes/skipped), [Guide for Go](https://mailset.app/send-email/go)

## Send many

Send several messages in one call and get one result per message, in the same order. A refused message never stops the rest.

### Example

```go
import (
	"context"
	"fmt"
	"log"

	mailset "mailset.app/go"
)

client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

results, err := client.SendMany(ctx, []mailset.Message{
	{
		From:    "Acme <hello@example.com>",
		To:      []string{"ana@example.org"},
		Subject: "Your invoice",
		Text:    "Invoice 8842 is ready.",
	},
	{
		From:    "Acme <hello@example.com>",
		To:      []string{"ben@example.org"},
		Subject: "Your invoice",
		Text:    "Invoice 8843 is ready.",
	},
})
if err != nil {
	log.Fatal(err)
}

for _, result := range results {
	if !result.OK {
		log.Println(result.MessageID, result.Error.Code)
		continue
	}
	fmt.Println(result.ID, result.Status)
}
```

More: [Send many messages at once](https://mailset.app/docs/recipes/batches)

## Promotional email

Send a newsletter or an offer with `mode: 'promotional'`. `{{mailset_unsubscribe}}` is a placeholder Mailset fills in for each message, with a signed one-click unsubscribe link unique to that recipient and that message. You never generate the link, and Mailset adds the matching `List-Unsubscribe` and `List-Unsubscribe-Post` headers itself.

### Example

```go
import (
	"context"
	"fmt"
	"log"
	"strings"

	mailset "mailset.app/go"
)

client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

text := strings.Join([]string{
	"Three new things this month.",
	"",
	"Leave this list: {{mailset_unsubscribe}}",
}, "\n")

html := strings.Join([]string{
	"<p>Three new things this month.</p>",
	`<a href="{{mailset_unsubscribe}}">Leave this list</a>`,
}, "\n")

sent, err := client.Send(ctx, mailset.Message{
	From:    "Acme News <news@news.example.com>",
	To:      []string{"ana@example.org"},
	Subject: "What shipped in March",
	Text:    text,
	HTML:    html,
	Mode:    mailset.ModePromotional,
})
if err != nil {
	log.Fatal(err)
}

fmt.Println(sent.ID, sent.Skipped)
```

### What Ana receives

Headers Mailset adds:

```text
List-Unsubscribe: <https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc>
List-Unsubscribe-Post: List-Unsubscribe=One-Click
```

The text part:

```text
Three new things this month.

Leave this list: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
```

The HTML part:

```html
<p>Three new things this month.</p>
<a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Leave this list</a>
```

A sample link. Mailset makes a new one for every message.

### What Ana receives without the placeholder

The text part:

```text
Three new things this month.

Unsubscribe: https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc
```

The HTML part:

```html
<p>Three new things this month.</p><p><a href="https://mailset.app/v1/unsubscribe/REjwEgpOG_zgHOqoFABR-wIAnGDtBkNRV-G7ho9WVWEYl8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1NjcKYW5hQGV4YW1wbGUub3JnCmRfMDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3Cm91dF8wMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc">Unsubscribe</a></p>
```

Mailset adds the last line of each part. The headers are the same.

More: [Honor unsubscribes and complaints](https://mailset.app/docs/recipes/unsubscribes), [Handle skipped recipients](https://mailset.app/docs/recipes/skipped)

## Idempotency

Name a send with `IdempotencyKey`, and sending it again after a timeout or a crash can’t send it twice.

### Example

```go
import (
	"context"
	"fmt"
	"log"

	mailset "mailset.app/go"
)

client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

receipt := mailset.Message{
	From:           "Acme <hello@example.com>",
	To:             []string{"ana@example.org"},
	Subject:        "Your receipt",
	Text:           "Thanks for your order.",
	IdempotencyKey: "receipt-8842",
}

first, err := client.Send(ctx, receipt)
if err != nil {
	log.Fatal(err)
}
// After a timeout or a crash, send it again.
// The same key answers the first receipt,
// and nothing goes out twice.
again, err := client.Send(ctx, receipt)
if err != nil {
	log.Fatal(err)
}

fmt.Println(first.ID == again.ID)
```

More: [Retry without sending twice](https://mailset.app/docs/recipes/retries)

## Check the key

Ask what the key may do now. Call it when your server starts and once a day: each call keeps the key alive.

### Example

```go
import (
	"context"
	"fmt"
	"log"
	"strings"
	"time"

	mailset "mailset.app/go"
)

client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

// When the server starts, and once a day.
status, err := client.Key.Check(ctx)
if err != nil {
	log.Fatal(err)
}

if status.Paused != nil {
	log.Println("Paused:", *status.Paused)
}
until := time.UnixMilli(status.ExpiresAt)
fmt.Println("Works until", until)
// A mailbox key sends as its mailbox.
for _, box := range status.Mailboxes {
	if box.Sending != mailset.SendingStateReady {
		log.Println(box.Address, box.Sending)
	}
}
// A domain key sends as the addresses it names.
for _, domain := range status.Domains {
	as := "any address"
	if domain.From != nil {
		as = strings.Join(domain.From, ", ")
	}
	fmt.Println(domain.Name, "sends as", as)
	if domain.Sending != mailset.SendingStateReady {
		log.Println(domain.Name, domain.Sending)
	}
}
```

More: [Keep a key alive](https://mailset.app/docs/recipes/keys)

## Delivery search

Look up what became of the mail this key sent, one line per recipient. For a support question or a nightly check.

### Example

```go
import (
	"context"
	"fmt"
	"log"

	mailset "mailset.app/go"
)

client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

// Did Ana get her receipt?
search := &mailset.DeliverySearchParams{
	Recipient: "ana@example.org",
	Since:     mailset.Day("2026-11-30"),
}
page, err := client.Delivery.Search(ctx, search)
if err != nil {
	log.Fatal(err)
}

for _, line := range page.Lines {
	fmt.Println(line.Status, line.Reason)
}
// Pass Next back as Cursor for the page after.
fmt.Println(page.Next)
```

More: [Handle bounces](https://mailset.app/docs/recipes/bounces)

## Webhooks

Check that a request came from Mailset and read its events. It needs no key and no client, so a service that only receives events uses it alone.

### Example

```go
import (
	"fmt"
	"io"
	"log"
	"os"

	mailset "mailset.app/go"
)

// handle checks one request from your org's hook:
// its body as it came, and its Mailset-Signature.
// It needs no client and no key.
func handle(body []byte, signature string) error {
	secret := os.Getenv("MAILSET_HOOK_SECRET")
	events, err := mailset.VerifyWebhook(
		body, signature, secret,
	)
	if err != nil {
		// unauthorized, expired or invalid_input:
		// answer 401.
		return err
	}
	for _, event := range events {
		switch event.Type {
		case mailset.EventBounced:
			if event.Bounce.Kind == mailset.BounceHard {
				fmt.Println("Stop writing to", event.Recipient)
			}
		case mailset.EventComplained,
			mailset.EventUnsubscribed:
			fmt.Println("Take", event.Recipient, "off the list")
		}
	}
	// Answer 2xx once the events are kept.
	// Until then Mailset posts the batch again.
	return nil
}
```

### In a web framework

The signature covers the body exactly as it arrived. Read the raw body before anything parses it, and hand that to the check: a body parsed as JSON and written out again no longer matches.

```go
import (
	"errors"
	"io"
	"log"
	"net/http"
	"os"

	mailset "mailset.app/go"
)

// hook is Mailset's webhook endpoint, a plain
// net/http handler.
func hook(w http.ResponseWriter, r *http.Request) {
	// The signature covers the body as it came: read
	// its bytes. A json.Decoder on r.Body loses them.
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "unreadable", http.StatusBadRequest)
		return
	}
	secret := os.Getenv("MAILSET_HOOK_SECRET")
	events, err := mailset.VerifyWebhookHeader(
		body, r.Header, secret,
	)
	var refused *mailset.Error
	if errors.As(err, &refused) {
		http.Error(w, refused.Code, http.StatusUnauthorized)
		return
	}
	for _, event := range events {
		if event.Type != mailset.EventBounced {
			continue
		}
		if event.Bounce.Kind == mailset.BounceHard {
			log.Println("Stop writing to", event.Recipient)
		}
	}
	// 2xx once the events are kept: until then
	// Mailset posts the batch again.
	w.WriteHeader(http.StatusNoContent)
}

func main() {
	http.HandleFunc("POST /hooks/mailset", hook)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

More: [Webhooks](https://mailset.app/docs/webhooks), [Handle bounces](https://mailset.app/docs/recipes/bounces)

## Errors

Every refusal is one kind of error. Branch on its `Code`, which never changes, and show its `Message` to people.

### Example

```go
import (
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	mailset "mailset.app/go"
)

client, err := mailset.NewClient() // reads MAILSET_KEY
if err != nil {
	log.Fatal(err)
}
ctx := context.Background()

_, err = client.Send(ctx, mailset.Message{
	From:      "Acme <hello@example.com>",
	To:        []string{"ana@example.org"},
	Subject:   "Your Acme code",
	Text:      "Your code is 123456.",
	DeliverBy: mailset.Within(10 * time.Minute),
})

var refused *mailset.Error
switch {
case err == nil:
	return
case !errors.As(err, &refused):
	log.Fatal(err)
case refused.RetryAt != 0:
	// limit_reached: it couldn't go before its deadline.
	fmt.Println("Try at", time.UnixMilli(refused.RetryAt))
case refused.Refusal == "recipient":
	fmt.Println("Ask them to check their address.")
default:
	log.Println(refused.Code, refused.Message)
}
```

### Retries and timeouts

A network failure or a 5xx answer is tried again, twice unless you set `MaxRetries`, waiting longer each time. One try may take 30 seconds unless you set `Timeout`. A refusal is never tried again: the same request gets the same answer.

More: [Errors and limits](https://mailset.app/docs/errors)

## Build the message yourself

Get the message a send would build, without sending it: for a queue of your own, or a call to the API from another service.

### Example

```go
import (
	"encoding/base64"
	"fmt"
	"log"

	mailset "mailset.app/go"
)

message := mailset.Message{
	From:    "Acme <hello@example.com>",
	To:      []string{"ana@example.org"},
	Subject: "Your Acme code",
	Text:    "Your code is 123456.",
}
raw, messageID, err := mailset.BuildMessage(message)
if err != nil {
	log.Fatal(err)
}

// The data that messages.submit takes.
data := base64.StdEncoding.EncodeToString(raw)

fmt.Println(messageID, len(data))
```

More: [messages.submit](https://mailset.app/docs/api/messages#messages.submit)

## Names

A field keeps its name in every SDK, in each language’s own case. The commands write `idempotencyKey`, and Go writes `IdempotencyKey`.

## Version and licence

This page is for version 0.7.0 of the Go SDK.

You may use the SDK and change it in your own apps and services, to call Mailset. You may not publish it or pass it on, by itself or inside another library.

Something missing, or not working as this page says? Ask us at https://mailset.app/support, or run `mailset feedback "<message>"` in a terminal.

---

© 2026 Intenseloop, Inc. Mailset’s site, docs and guides are copyrighted. You may read them and use their code to build with Mailset. Don’t republish them or use them to build a copy of Mailset. Terms: https://mailset.app/terms#content