---
title: Go SDK
description: Use BillionSend from Go with the github.com/billionsend/billionsend-go module.
---

The `github.com/billionsend/billionsend-go` module is the BillionSend client for Go. It covers every operation of the [API reference](/docs/api-reference): sending, domains, contacts, broadcasts, templates, webhooks, inboxes with their threads and drafts, live inbox events and agent sign-up. Its types come from the API's OpenAPI document. The source is [billionsend/billionsend-go](https://github.com/billionsend/billionsend-go) on GitHub.

## Install

Needs Go 1.23 or newer. The module uses the standard library only.

```sh
go get github.com/billionsend/billionsend-go@v0.1.3
```

## Send an email

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/billionsend/billionsend-go"
)

func main() {
	ctx := context.Background()
	client := billionsend.NewClient() // reads BILLIONSEND_API_KEY

	sent, err := client.Emails.Send(ctx, &billionsend.SendEmailRequest{
		From:    "Acme <hello@acme.dev>",
		To:      []string{"ana@example.com"},
		Subject: "Welcome to Acme",
		HTML:    billionsend.String("<p>Glad you are here.</p>"),
	}, billionsend.WithIdempotencyKey("welcome/ana"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(sent.ID)
}
```

`billionsend.NewClient(billionsend.WithAPIKey("bs_..."))` takes the key directly; `WithBaseURL`, `WithTimeout` (per attempt, default 60 s), `WithMaxRetries`, `WithHTTPClient` and `WithHeader` set the rest. `BILLIONSEND_BASE_URL` overrides the API URL.

## Method names

Each operation is a method named after its id in the [API reference](/docs/api-reference), each dotted segment in Go's capitals: `emails.send` is `client.Emails.Send`, `emails.receiving.attachments.list` is `client.Emails.Receiving.Attachments.List`. `emails.metrics` is `client.Emails.Metrics.Get`, beside `Links`, `Countries` and `Clients`.

A method takes the context, the path parameters in order, the request body (`*XxxRequest`), the query and header parameters (`*XxxParams`), then options. Optional fields are pointers, made with `billionsend.String`, `Int64`, `Float64` and `Bool`; a field that takes more than one shape, such as an address or a list of them, is typed `any`.

## Idempotency and retries

The eight sending operations (`Emails.Send`, `Emails.Batch`, received-mail replies and forwards, `Inboxes.Send`, `Inboxes.Drafts.Send`, thread replies and forwards) always send an `Idempotency-Key`. Without `WithIdempotencyKey`, each call makes one up that its retries reuse, so a retry after a timeout never sends twice; your own key also makes a repeat from another process safe.

Failures worth retrying are retried twice by default: 429, 5xx, timeouts, network errors, and the `409 concurrent_idempotent_requests` answered while the first attempt with the same key is still running. Only requests safe to repeat are retried: `GET`, `PUT`, `DELETE` and the sending operations. The client waits as `Retry-After` asks, up to a minute, and otherwise backs off exponentially from 500 ms to 8 s. `WithRequestTimeout`, `WithRequestMaxRetries`, `WithRequestHeader` and `WithResponseHeaders` work per call.

## Errors

A failed call returns `*ValidationError` (400, 422), `*AuthenticationError` (401, or no key configured), `*PermissionDeniedError` (403), `*NotFoundError` (404), `*ConflictError` (409), `*RateLimitError` (429, with `RetryAfter`), `*APIError` (5xx), `*APIConnectionError` (no answer) or `*APITimeoutError` (the attempt timed out). Each unwraps to `*billionsend.Error`, with `StatusCode`, `Name` (the API's error name), `Message` and `RequestID`, the answer's `x-request-id`, which is the request's id on the dashboard's Logs page.

```go
_, err := client.Emails.Get(ctx, id)
var notFound *billionsend.NotFoundError
var apiErr *billionsend.Error
switch {
case errors.As(err, &notFound):
	// no such email
case errors.As(err, &apiErr):
	log.Printf("%d %s: %s (request %s)", apiErr.StatusCode, apiErr.Name, apiErr.Message, apiErr.RequestID)
}
```

## Lists

List methods return one page. Every cursor list also has an `...All` iterator that fetches the next pages as it goes, backward when `Before` is set:

```go
for contact, err := range client.Contacts.ListAll(ctx, &billionsend.ContactsListParams{Limit: billionsend.Int64(100)}) {
	if err != nil {
		return err
	}
	fmt.Println(contact.Email)
}
```

## An agent's inbox

Wait for new mail on the [event stream](/docs/inboxes) and reply in its thread:

```go
stream, err := client.Inboxes.Events.StreamInbox(ctx, "support@acme.dev", &billionsend.InboxesEventsStreamInboxParams{
	Types: billionsend.String("inbox.email.received"),
})
if err != nil {
	return err
}
defer stream.Close()

for item, err := range stream.Events() {
	if err != nil {
		return err // reconnecting ran out, or the key stopped working
	}
	ev, ok := item.(*billionsend.InboxStreamEvent)
	if !ok {
		continue // a *StreamGapEvent: events may be missing, read the threads again
	}
	d := ev.Data.Data
	_, err := client.Inboxes.Threads.Emails.Reply(ctx, ev.Data.InboxID, d.ThreadID, d.EmailID,
		&billionsend.InboxReplyRequest{Text: billionsend.String("Thanks, we are on it.")},
		billionsend.WithIdempotencyKey("reply/"+d.EmailID),
	)
	if err != nil {
		return err
	}
}
```

The stream reconnects with `Last-Event-ID` when the connection drops and replays what it missed; keep `stream.LastEventID()` and pass it back with `WithLastEventID` to resume after a restart. A `*StreamGapEvent` comes once when the stream resumes from more than 24 hours back. `WithMaxReconnects` (default 5), `WithReconnectDelay` and `WithoutReconnect` tune reconnecting. One inbox's stream ends after that inbox is deleted or expires; `client.Inboxes.Events.Stream` follows every inbox the key can read.

## Verify webhooks

`VerifyWebhook` checks a [webhook](/docs/concepts/webhooks) delivery's signature and timestamp with the endpoint's `whsec_` secret and returns the parsed event. Pass the body exactly as it arrived:

```go
http.HandleFunc("/webhooks/billionsend", func(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)
	event, err := billionsend.VerifyWebhook(body, r.Header, os.Getenv("BILLIONSEND_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	log.Print(event.Type)
	w.WriteHeader(http.StatusNoContent)
})
```

A delivery older than five minutes is refused, and during a secret rotation either secret verifies.
