# Send emails with Go

> Call the MailBlastr REST API from Go with the standard-library net/http.

MailBlastr does not yet publish a Go module, but the standard library is all you need: `net/http` plus `encoding/json` send a `POST /emails` request with no third-party dependency. Marshal the body, set the `Authorization` header, and decode the response.

This guide sends a single email. Node.js projects can use `npm install mailblastr` instead — see [Send emails with Node.js](https://www.mailblastr.com/docs/integrations/nodejs).

## Prerequisites

1. A **verified domain** for your `from` address. ([guide](https://www.mailblastr.com/docs/domains/managing))
2. An **API key** (`mb_...`), read from `os.Getenv("MAILBLASTR_API_KEY")`. ([Authentication](https://www.mailblastr.com/docs/authentication))
3. Go 1.16+ (standard library only).

## Send an email

**main.go**

```go
package main

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

func main() {
	payload := map[string]any{
		"from":    "Acme <hello@yourdomain.com>",
		"to":      []string{"delivered@example.com"},
		"subject": "Hello from Go",
		"html":    "<p>Sent with net/http 🐹</p>",
	}
	body, _ := json.Marshal(payload)

	req, _ := http.NewRequest("POST", "https://www.mailblastr.com/api/emails", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("MAILBLASTR_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	// MailBlastr returns { statusCode, name, message } on error.
	if res.StatusCode >= 400 {
		var e struct{ Name, Message string }
		json.NewDecoder(res.Body).Decode(&e)
		panic(fmt.Sprintf("MailBlastr %s: %s", e.Name, e.Message))
	}

	var out struct {
		ID string `json:"id"`
	}
	json.NewDecoder(res.Body).Decode(&out)
	fmt.Println("Sent email", out.ID)
}
```

## Handling the response

A successful send returns HTTP `200` and a JSON body you can decode into a struct with an `id` field. On failure the status is non-2xx and the body is `{ statusCode, name, message }` — check `res.StatusCode` before decoding the `id`, as above. Keep the `id` to [retrieve the email](https://www.mailblastr.com/docs/api/emails-get) or correlate [webhook](https://www.mailblastr.com/docs/webhooks/overview) events.

```json
{
  "id": "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794"
}
```

> **Warning:** Read the `mb_` API key from the environment (or your secrets manager) and keep it server-side. Never embed it in a client binary, a mobile app, or anything shipped to users — the key can send email as you.

## Next steps

- See the full [Send Email API](https://www.mailblastr.com/docs/api/emails-send) reference for every body field.
- Read [Authentication](https://www.mailblastr.com/docs/authentication) for key permissions.
- Start from the [Quickstart](https://www.mailblastr.com/docs/quickstart).
