# Send Email with Go (Golang): API Tutorial

> Send email with Go using net/http and an email API: a dependency-free client with retries, templates, attachments, batches of 100 and an HTTP handler.

Canonical: https://www.cresca.xyz/blog/send-email-golang
Author: Lalit Kumar Jangid
Published: 2026-10-27
Last updated: 2026-10-30

Go ships `net/smtp`, but its own documentation calls the package frozen: it takes no new features. It also leaves you managing connections, TLS and SMTP replies. There is a shorter path to **send email with Go**. An email API needs `net/http` and `encoding/json` and nothing else: one POST, and Cresca answers with an email id and sends from your verified domain within seconds. Below, a small dependency-free `cresca` package, then templates, attachments, batches and an HTTP handler.

**TL;DR**

- POST JSON to `https://api.cresca.xyz/api/v1/emails` with `Authorization: Bearer <key>`.
- Standard library only: net/http, encoding/json, context.
- Every failure is an `error` value. Retry 429, 5xx and transport errors with an `Idempotency-Key`, so a retry can't send twice.
- Up to 100 emails go in one batch call.

## Before you write any Go

- **Go 1.21 or newer.** The batch loop uses the built-in `min` and the handler uses `context.WithoutCancel`, both new in 1.21.
- **A Cresca account that can send.** That means a domain verified on [Sending Domains](https://app.cresca.xyz/sending-domains), a sender address on it (`hello@acme.com`, say) and a *Sending access* key from [API keys](https://app.cresca.xyz/api-keys). Follow the [email API quickstart](https://www.cresca.xyz/docs/quickstart) for each one.
- **`CRESCA_API_KEY` in the environment.** You see the `cr_live_` key only once. The package reads it with `os.Getenv` per request, so check it in `main` and exit if it's empty, rather than failing on the first signup.

## Send email with Go: the basic request

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload, err := json.Marshal(map[string]any{
		"from":    "Acme <hello@acme.com>",
		"to":      "ana@example.com",
		"subject": "Welcome to Acme",
		"html":    "<p>Hi Ana, your account is ready.</p>",
	})
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest(http.MethodPost, "https://api.cresca.xyz/api/v1/emails", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("CRESCA_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 10 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var body struct {
		ID      string `json:"id"`
		Name    string `json:"name"`
		Message string `json:"message"`
	}
	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode != http.StatusOK {
		log.Fatalf("%s: %s", body.Name, body.Message)
	}
	fmt.Println(body.ID)
}
```

A good response is `200 OK` with `{"id": "4ef9a417-..."}`. Two Go details: the zero-value `http.Client` has no timeout and will wait forever on a stuck connection, so always set one. And `json.Marshal` writes `<` and `>` as `\u003c` and `\u003e`. That is valid JSON and the HTML arrives unchanged. Cresca builds the plain-text part from `html` unless you send your own `text`.

## A small Go client with retries

In Go a failed send is an `error` value, and it can come from two places. `client.Do` returns a non-nil error (a `*url.Error`) when no response arrived at all: DNS, a refused connection, a timeout. A 4xx or 5xx response is not an error to `net/http`, so you have to turn it into one yourself. The `cresca` package below does that, plus two more things production needs:

- **A typed `*cresca.Error`.** Error bodies look like `{"statusCode": 422, "name": "validation_error", "message": "..."}`. The package decodes them into `Error`, which implements `error`, so callers use `errors.As` and compare `Name`. Don't match on `Message`, which can be reworded.
- **Retries for failures that can pass later.** Transport errors, 429 `rate_limit_exceeded` and 5xx get up to four attempts. The wait comes from `Retry-After` when present and from exponential backoff otherwise, inside a `select` on `ctx.Done()`, so a canceled context ends the loop straight away. Other 4xx responses return immediately; a bad request fails the same way twice.
- **An `Idempotency-Key` header.** When the response is lost after Cresca has accepted the email, the next attempt sends the same key and receives the original result, not a second email. A key is remembered for 24 hours. Derive it from the event (`welcome/user-123`, `invoice/inv-2026-0042`), never from `time.Now()` or a random UUID. More in [idempotency](https://www.cresca.xyz/docs/idempotency).

```go
// Package cresca is a small client for the Cresca email API.
package cresca

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"math/rand"
	"net/http"
	"os"
	"strconv"
	"time"
)

const (
	apiURL   = "https://api.cresca.xyz/api/v1"
	attempts = 4
)

var client = &http.Client{Timeout: 10 * time.Second}

type Email struct {
	From        string       `json:"from,omitempty"`
	To          []string     `json:"to"`
	ReplyTo     string       `json:"reply_to,omitempty"`
	Subject     string       `json:"subject,omitempty"`
	HTML        string       `json:"html,omitempty"`
	Text        string       `json:"text,omitempty"`
	Template    *Template    `json:"template,omitempty"`
	Attachments []Attachment `json:"attachments,omitempty"`
}

type Template struct {
	ID        string         `json:"id"`
	Variables map[string]any `json:"variables,omitempty"`
}

type Attachment struct {
	Filename    string `json:"filename"`
	Content     []byte `json:"content"` // encoding/json sends []byte as base64
	ContentType string `json:"content_type,omitempty"`
}

// Error is an error response from the API. Branch on Name.
type Error struct {
	Status  int
	Name    string `json:"name"`
	Message string `json:"message"`
}

func (e *Error) Error() string {
	return fmt.Sprintf("cresca: %d %s: %s", e.Status, e.Name, e.Message)
}

// Post sends payload to path, retrying where it is safe, and decodes the
// response into out.
func Post(ctx context.Context, path string, payload any, idempotencyKey string, out any) error {
	data, err := json.Marshal(payload)
	if err != nil {
		return err
	}
	for attempt := 1; ; attempt++ {
		req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL+path, bytes.NewReader(data))
		if err != nil {
			return err
		}
		req.Header.Set("Authorization", "Bearer "+os.Getenv("CRESCA_API_KEY"))
		req.Header.Set("Content-Type", "application/json")
		if idempotencyKey != "" {
			req.Header.Set("Idempotency-Key", idempotencyKey)
		}

		wait, retryable, err := do(req, out)
		if err == nil {
			return nil
		}
		if !retryable || attempt == attempts {
			return err
		}
		if wait == 0 {
			// 1s, 2s, 4s... plus up to 250 ms of jitter.
			wait = time.Duration(1<<(attempt-1))*time.Second + time.Duration(rand.Intn(250))*time.Millisecond
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(wait):
		}
	}
}

func do(req *http.Request, out any) (wait time.Duration, retryable bool, err error) {
	res, err := client.Do(req)
	if err != nil {
		return 0, true, err // network error or timeout
	}
	defer res.Body.Close()

	if res.StatusCode == http.StatusOK {
		return 0, false, json.NewDecoder(res.Body).Decode(out)
	}
	apiErr := &Error{Status: res.StatusCode}
	_ = json.NewDecoder(res.Body).Decode(apiErr) // a proxy error may have no JSON body
	retryable = res.StatusCode >= 500 ||
		(res.StatusCode == http.StatusTooManyRequests && apiErr.Name != "monthly_quota_exceeded") ||
		apiErr.Name == "concurrent_idempotent_requests"
	if seconds, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil {
		wait = time.Duration(seconds) * time.Second
	}
	return wait, retryable, apiErr
}
```

The request is rebuilt on each attempt with a fresh `bytes.NewReader`, since `Do` consumes the body and a reused request would go out empty. The package-level `http.Client` is shared on purpose: it pools connections and is safe for concurrent use.

Using it:

```go
var sent struct {
	ID string `json:"id"`
}
err := cresca.Post(ctx, "/emails", cresca.Email{
	From:    "Acme <hello@acme.com>",
	To:      []string{user.Email},
	Subject: "Welcome to Acme",
	HTML:    "<p>Hi " + html.EscapeString(user.FirstName) + ", your account is ready.</p>",
}, "welcome/"+user.ID, &sent)

var apiErr *cresca.Error
if errors.As(err, &apiErr) && apiErr.Name == "invalid_from_address" {
	// Configuration problem: alert someone instead of retrying.
}
```

`html.EscapeString` stops a user's name from injecting markup. `errors.As` pulls out the `*cresca.Error`, so a misconfigured sender can alert a person instead of being retried.

## Send a template with variables

Concatenating HTML in Go is tedious. Cresca's template editor lets you lay the email out once, put placeholders such as `{{{RESET_LINK}}}` where values go, and publish. Go code then sends only an alias and a `map[string]any`. This is Cresca's syntax, not `html/template`. Sends render the *published* version, never a draft, and every value is HTML-escaped. Leave out a variable that has no fallback and `Post` returns a 422 `validation_error` naming it. See [templates and variables](https://www.cresca.xyz/docs/templates).

```go
err := cresca.Post(ctx, "/emails", cresca.Email{
	To: []string{user.Email},
	Template: &cresca.Template{
		ID:        "password-reset", // the template's alias or id
		Variables: map[string]any{"NAME": user.FirstName, "RESET_LINK": resetURL},
	},
}, "password-reset/"+resetRequestID, &sent)
```

`Template` is a pointer tagged `omitempty`, so it drops out of the JSON for plain HTML sends. Map keys go out exactly as written, which keeps `"NAME"` upper case.

## Add attachments

`encoding/json` encodes a `[]byte` field as standard base64, the format the API expects, so you read the file with `os.ReadFile` and assign the bytes. The limit is 20 files and 7 MB in total per email. Fields are `filename`, `content` and an optional `content_type`. Cresca rejects executables (.exe, .js), and URL attachments aren't supported yet.

```go
pdf, err := os.ReadFile("invoices/inv-2026-0042.pdf")
if err != nil {
	return err
}
err = cresca.Post(ctx, "/emails", cresca.Email{
	From:    "Acme Billing <billing@acme.com>",
	To:      []string{customer.Email},
	Subject: "Your invoice INV-2026-0042",
	HTML:    "<p>Thanks for your payment. Your invoice is attached.</p>",
	Attachments: []cresca.Attachment{
		{Filename: "inv-2026-0042.pdf", Content: pdf, ContentType: "application/pdf"},
	},
}, "invoice/inv-2026-0042", &sent)
```

Inline images use `content_id`, referenced from the HTML as `<img src="cid:logo">`. The `Attachment` struct above has no such field, so add `` ContentID string `json:"content_id,omitempty"` `` when you need one.

## Batch sends: 100 emails per call

`POST /emails/batch` takes a slice of up to 100 `Email` values. Every element supports the single-send fields apart from `attachments` and `scheduled_at`. One invalid element rejects the whole batch, and the error message points at it by zero-based index. On success, `{"data": [{"id": "..."}, ...]}` comes back in the same order, and the call uses one request of your rate limit.

```go
emails := make([]cresca.Email, 0, len(users))
for _, u := range users {
	emails = append(emails, cresca.Email{
		From:    "Acme <hello@acme.com>",
		To:      []string{u.Email},
		Subject: "Your weekly summary",
		HTML:    renderSummary(u),
	})
}

for i := 0; i < len(emails); i += 100 {
	chunk := emails[i:min(i+100, len(emails))]
	var result struct {
		Data []struct {
			ID string `json:"id"`
		} `json:"data"`
	}
	key := fmt.Sprintf("weekly-summary/2026-10-27/%d", i/100)
	if err := cresca.Post(ctx, "/emails/batch", chunk, key, &result); err != nil {
		return err
	}
	log.Printf("batch %d: %d emails accepted", i/100, len(result.Data))
}
```

Slicing doesn't copy, and the key built from the date and chunk number means a rerun of the job within 24 hours won't resend chunks that already went out.

Batching beats fanning out with goroutines, because the rate limit counts requests from every goroutine and server. Free allows 2 requests per second, Professional 10, Premium 20, Ultra 50 and Enterprise 100. One email can reach 50 recipients across to, cc and bcc (the struct above only has `To`, so add fields if you need the others), and every recipient uses one email from your monthly allowance.

## Send email from an HTTP handler

The context you pass decides what can stop a send. `r.Context()` is canceled when the client disconnects, which is not what you want for a welcome email. The handler below keeps the request's values but drops its cancellation with `context.WithoutCancel`, then sets its own 30-second deadline:

```go
func signupHandler(w http.ResponseWriter, r *http.Request) {
	user, err := createUser(r) // your own code
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Detach from the request so a closed browser tab does not cancel the email.
	ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 30*time.Second)
	defer cancel()

	var sent struct {
		ID string `json:"id"`
	}
	err = cresca.Post(ctx, "/emails", cresca.Email{
		To:       []string{user.Email},
		Template: &cresca.Template{ID: "welcome", Variables: map[string]any{"NAME": user.FirstName}},
	}, "welcome/"+user.ID, &sent)
	if err != nil {
		log.Printf("welcome email for %s failed: %v", user.ID, err)
	}

	w.WriteHeader(http.StatusCreated)
}
```

That deadline covers the whole retry loop. Each attempt still has the client's 10-second timeout, so slow attempts plus backoff can run past 30 seconds, and then `Post` gives up with an error that matches `context.DeadlineExceeded` under `errors.Is`. The handler also waits for the send. If that latency matters, hand the email to a queue and keep the idempotency key, so a redelivered job doesn't send twice.

## net/smtp or an email API?

The `net/smtp` docs mark it frozen and point to third-party packages; go-mail is a good one when you operate an SMTP server. Going over HTTP keeps your go.mod free of mail libraries, gives you errors with a stable `name`, and idempotency keys make retrying harmless. Since Cresca doesn't run an SMTP relay yet, the API is how Go code reaches it.

## Errors to handle when you send email with Go

What `Post` returns for common errors. Every name is documented on the [errors page](https://www.cresca.xyz/docs/errors).

| Status | Name | Cause | What Post returns |
| --- | --- | --- | --- |
| 403 | `invalid_from_address` | The From field isn't an active sender on a verified domain. | `*cresca.Error` at once. Fix the sender. |
| 422 | `validation_error` | A bad field value or a missing template variable. | `*cresca.Error` at once. |
| 422 | `missing_required_field` | To, From or Subject is empty and no template fills it. | `*cresca.Error` at once. |
| 429 | `rate_limit_exceeded` | Too many requests this second. | Retries after Retry-After. |
| 429 | `monthly_quota_exceeded` | The monthly email allowance is spent. | `*cresca.Error` at once. |
| 409 | `concurrent_idempotent_requests` | An earlier request with this key is still running. | Retries with backoff. |
| 5xx | `application_error` | A server-side failure at Cresca. | Retries with backoff. |
| none | transport | DNS, connection or timeout failure. | Retries, then the last `*url.Error`. |

Addresses Cresca has suppressed (past hard bounces, complaints, unsubscribes) are dropped without an error and `Post` returns `nil`, so a nil error doesn't mean every address got the email. See [suppression](https://www.cresca.xyz/docs/suppression).

## Confirm the email was delivered

`err == nil` means Cresca accepted the email. Delivery is reported afterwards: check the [Transactional](https://app.cresca.xyz/transactional) view in the app, or query the email by id using a full-access key, since sending keys can't read logs:

```bash
curl https://api.cresca.xyz/api/v1/emails/4ef9a417-02e9-4d39-ad75-9611e0fcc33c \
  -H "Authorization: Bearer $CRESCA_API_KEY"
```

Poll `last_event`: `queued`, then `sent`, then a final `delivered` or `bounced`. [Email lifecycle](https://www.cresca.xyz/docs/email-lifecycle) explains every status.

## Go questions

### Is the client safe to use from many goroutines?

Yes. Its only shared state is the `http.Client`, which is safe for concurrent use. The rate limit still applies across all goroutines and processes, so batch large sends.

### Why does my request body show \\u003c instead of <?

`encoding/json` escapes `<`, `>` and `&` by default so JSON can sit safely inside HTML. Any JSON parser reads them back as the original characters. If you want them literal in logs, encode with a `json.Encoder` and call `SetEscapeHTML(false)`.

### Do I need a third-party module or an official SDK?

No. Cresca has no official Go SDK, and the standard library already speaks HTTPS and JSON. Copy the package into something like `internal/cresca` and adapt it.

## The same tutorial in other languages

[Node.js](https://www.cresca.xyz/blog/send-email-nodejs) · [Python](https://www.cresca.xyz/blog/send-email-python) · [PHP](https://www.cresca.xyz/blog/send-email-php) · [Ruby](https://www.cresca.xyz/blog/send-email-ruby) · [Java](https://www.cresca.xyz/blog/send-email-java) · [C# and .NET](https://www.cresca.xyz/blog/send-email-csharp) · [Next.js](https://www.cresca.xyz/blog/send-email-nextjs) · [Laravel](https://www.cresca.xyz/blog/send-email-laravel) · [Django](https://www.cresca.xyz/blog/send-email-django) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

The [send email API guide](https://www.cresca.xyz/blog/send-email-api) lists every field with cURL. For the wider picture, see the [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api), and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) goes deeper on the trade-off.

## Send your first email from Go

With a verified domain and a sending key, `go run` on the first example sends a real email. **[Create a Cresca account](https://app.cresca.xyz/signup)**. It's free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. Next stops: the [quickstart](https://www.cresca.xyz/docs/quickstart), then the full [API docs](https://www.cresca.xyz/docs).
