How to Send Email from Go (Golang): HTML Templates, a Mailer Package and an API

Send email in Golang with a Go email library and API: HTML email from html/template files, a reusable mailer package, attachments and threaded replies.

By · · Updated · 20 min read

shell code from this guide, in a terminal, sending or reading email with Mailcycle

To send email from Go (Golang), most tutorials reach for net/smtp or a gomail-style library, then spend the next hour on SMTP hosts, ports, TLS and MIME boundaries. This guide takes the other route: a Go email library backed by an email API. You’ll send email from Go with one function call over HTTPS, from a plain program and from a net/http handler. Then you’ll render HTML email from html/template files with a plain-text alternative, wrap the whole thing in a small mailer package your handlers share, add attachments and threaded replies, and receive the replies in the same inbox.

We’ll use Mailcycle’s Go SDK, mailcycle.email/go. It’s a small, flat package with plain structs and errors you can switch on, and the Go SDK page has its quickstart. Every program here builds and passes go vet against v0.11.0, and the template and mailer code was run live against a Mailcycle account.

This post is the Go chapter of send email from any language. If Go isn’t your only stack, the same flow is written up for Python, TypeScript and Rust.

To read mail as well as send it, see How to receive email in Go: create an address, wait for a message, save attachments and handle a webhook.

Quick answer: how do you send an email in Go (Golang)?

Install the SDK with go get mailcycle.email/go, create a client from an API key in an environment variable, and call Messages().Send with a From address on your account, a To, a subject and a text body. It’s a single HTTPS request: no SMTP server, no port 587, no hand-built MIME.

package main

import (
	"log"
	"os"

	"mailcycle.email/go" // package mailcycle
)

func main() {
	mc, err := mailcycle.WithAPIKey(os.Getenv("MAILCYCLE_API_KEY"), "", mailcycle.Options{})
	if err != nil {
		log.Fatal(err)
	}

	sent, err := mc.Messages().Send(mailcycle.Outgoing{
		From:    os.Getenv("MAILCYCLE_FROM"), // an address on your account
		To:      "someone@example.com",
		Subject: "Hello from Go",
		Text:    "Sent with the Mailcycle Go SDK.",
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("sent", sent.MessageID)
}

That’s the whole thing. The rest of this guide turns it into production code: a handler with sensible timeouts, HTML and attachments, replies, error handling and tests.

What you’ll build: a Golang email sender

By the end you’ll have:

  • a POST /sign-in/code endpoint on Go 1.22+ ServeMux patterns that emails a one-time sign-in code;
  • HTML receipts rendered from html/template files embedded in the binary, with a text/template plain-text part;
  • a reusable mailer package that wraps the client, so every handler sends with one method call;
  • an invoice email with a PDF attachment and an inline logo from //go:embed;
  • a send-then-wait flow that emails a customer, blocks until they reply, and answers in the same thread;
  • a webhook handler that hears about incoming replies the moment they land;
  • error handling by code, with retries only where a retry is safe, and unit tests that never touch the network.

These are the jobs Mailcycle is for: transactional and notification mail, sign-in and verification flows, and app or agent replies, sent from addresses you own, one recipient per call.

Flow: your Go code calls the Go SDK, Mailcycle sends the email from your address, and the recipient gets it
Your Go code calls the Go SDK, and Mailcycle sends the email from your address.

Prerequisites for sending email in Golang

  • Go 1.26 or later. The SDK’s go.mod says go 1.26.0. Check with go version.
  • A Mailcycle account on the Scale plan, or the free 7-day Scale trial. Sending with an API key starts at Scale, and the trial needs no card. Sign up at app.mailcycle.email/operator/signup; there’s no email or password, because the account is a 12-word recovery phrase made on your device.
  • An API key. In the app, open API, then the Keys tab, name the key and choose Create key. Copy the token now: it starts with mak_ and is shown once.
  • An address to send from, created in the app under Email addresses or with the SDK in step 2.
  • Your recovery phrase, only for the parts that read mail (steps 2, 7 and 8). Sending alone needs just the key.

Step 1: Install the Golang email SDK

In your module:

go get mailcycle.email/go

The module is served from mailcycle.email rather than a Git host, and its documentation is on pkg.go.dev. The import path ends in /go but the package is named mailcycle, so add a comment to save the next reader a lookup:

import "mailcycle.email/go" // package mailcycle

Then put your credentials in the environment. Never hard-code them, and never ship an API key inside software you distribute.

export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_FROM="receipts-x7k2@..."          # an address on your account
export MAILCYCLE_PHRASE="twelve words ..."          # only where you read mail

Step 2: Authenticate and create a sending address

There are two ways to build a client from an API key, and the difference is the second argument:

// Send-only: no phrase, no network call at construction.
mc, err := mailcycle.WithAPIKey(os.Getenv("MAILCYCLE_API_KEY"), "", mailcycle.Options{})

// Send and read: the phrase is checked against the key's account first.
reader, err := mailcycle.WithAPIKey(os.Getenv("MAILCYCLE_API_KEY"), os.Getenv("MAILCYCLE_PHRASE"), mailcycle.Options{})

A send-only client is what most web services want. It can send, list addresses and manage metadata, but it can’t open mail, so a leaked process environment doesn’t expose anyone’s inbox. Give the phrase only to the process that reads replies.

From must be one of your account’s addresses; anything else is refused with not_your_address. If you don’t have one yet, create it once with a client that holds the phrase. The address’s public key is derived here and uploaded, so the mail server can seal what arrives:

package main

import (
	"fmt"
	"log"
	"os"

	"mailcycle.email/go" // package mailcycle
)

func main() {
	mc, err := mailcycle.WithAPIKey(
		os.Getenv("MAILCYCLE_API_KEY"),
		os.Getenv("MAILCYCLE_PHRASE"), // derives the address's key on this machine
		mailcycle.Options{},
	)
	if err != nil {
		log.Fatal(err)
	}

	address, err := mc.Addresses().Create(mailcycle.NewAddress{
		Prefix: "receipts",
		Label:  "Order receipts",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(address.EmailAddress, address.ID) // receipts-x7k2@... ibx_...
}

Prefix gives you receipts- plus a random ending on a shared domain. On Scale you can choose the whole name with LocalPart, and use your own domain, so codes come from signin@yourcompany.com. The email addresses guide covers the other options.

Step 3: Send email from a Go HTTP handler

Here’s the endpoint most apps need first: the user types their address, and you email them a sign-in code. It uses Go 1.22’s method-and-path patterns in http.NewServeMux, so a GET to the same path gets a 405 without any code from you.

package main

import (
	"crypto/rand"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"math/big"
	"net/http"
	"net/mail"
	"os"
	"time"

	"mailcycle.email/go" // package mailcycle
)

type server struct {
	mail *mailcycle.Messages
	from string
}

func main() {
	mc, err := mailcycle.WithAPIKey(
		os.Getenv("MAILCYCLE_API_KEY"),
		"", // no phrase: this service only sends
		mailcycle.Options{Timeout: 10 * time.Second},
	)
	if err != nil {
		log.Fatal(err)
	}

	s := &server{mail: mc.Messages(), from: os.Getenv("MAILCYCLE_FROM")}

	mux := http.NewServeMux()
	mux.HandleFunc("POST /sign-in/code", s.sendSignInCode)
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	})

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      15 * time.Second, // longer than the SDK's 10s
		IdleTimeout:       60 * time.Second,
	}
	log.Fatal(srv.ListenAndServe())
}

func (s *server) sendSignInCode(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, 1<<10)

	var req struct {
		Email string `json:"email"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "expected {\"email\": \"...\"}", http.StatusBadRequest)
		return
	}
	to, err := mail.ParseAddress(req.Email)
	if err != nil {
		http.Error(w, "that is not an email address", http.StatusBadRequest)
		return
	}

	code, err := sixDigits()
	if err != nil {
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
	// Store a hash of code against to.Address with an expiry here.

	// The client may have given up while we validated. Don't send for nobody.
	if err := r.Context().Err(); err != nil {
		return
	}

	_, err = s.mail.Send(mailcycle.Outgoing{
		From:     s.from,
		FromName: "Acme sign-in",
		To:       to.Address,
		Subject:  "Your Acme sign-in code: " + code,
		Text:     "Your code is " + code + ". It expires in 10 minutes.\n\nIf you didn't ask for it, ignore this email.",
	})
	if err != nil {
		var apiErr *mailcycle.APIError
		if errors.As(err, &apiErr) && apiErr.Status == http.StatusTooManyRequests {
			http.Error(w, "too many codes sent, try again shortly", http.StatusTooManyRequests)
			return
		}
		log.Printf("send sign-in code: %v", err)
		http.Error(w, "could not send the code", http.StatusBadGateway)
		return
	}
	w.WriteHeader(http.StatusAccepted)
}

func sixDigits() (string, error) {
	n, err := rand.Int(rand.Reader, big.NewInt(1_000_000))
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%06d", n.Int64()), nil
}

A few choices in there are worth spelling out.

Parse, then send the bare address. net/mail.ParseAddress accepts Sam <sam@example.com> and gives you to.Address, sam@example.com. The API takes one plain recipient per call and refuses an address containing characters such as <, > or , with invalid_address, so normalising first turns a confusing API error into a clean 400 from you.

Timeouts, layered. The SDK’s calls are synchronous and don’t take a context.Context. Instead, every HTTP request it makes is bounded by Options.Timeout, 30 seconds unless you set it. Set it below your server’s WriteTimeout (10 seconds against 15 here), so a slow upstream turns into an error you can answer rather than a connection the server cuts.

Check the context before sending, not during. r.Context() is cancelled when the client disconnects. Checking it just before Send means a user who closed the tab doesn’t get a code they’ll never type. Once a send has started, let it finish: abandoning it halfway leaves you not knowing whether the email went.

FromName sets the display name on the From line, so the inbox shows “Acme sign-in” rather than a bare address. It’s one line, up to 78 characters.

Try it locally:

go run . &
curl -i -X POST localhost:8080/sign-in/code \
  -H "Content-Type: application/json" \
  -d '{"email": "you@example.com"}'

A 202 Accepted means the code is on its way. If you use Gin, Echo or Chi, the body of sendSignInCode moves across unchanged; only the routing and how you read JSON differ.

Step 4: Send HTML email in Go with html/template

Most mail an app sends is HTML: receipts, invites, password resets. In Go the right tool is the standard library’s html/template. It’s the same template language as text/template, but it knows it is writing HTML, so it escapes every value for where it lands: text in a <td> is HTML-escaped, a value in an href is checked as a URL, and a customer who calls themselves <script> stays plain text. Build the HTML with fmt.Sprintf or string concatenation and you get none of that.

Every send also needs a plain-text body. The API requires Text, and the message goes out with both parts, so a mail client that shows HTML shows the template and one that doesn’t, a watch or a terminal mail reader, shows the text. Previews and notifications use the text as well. So a Go email template is really a pair: receipt.html for html/template and receipt.txt for text/template, fed the same data.

The Go email template files

Put the templates in a templates folder next to your code. The HTML part, templates/receipt.html:

<!doctype html>
<html>
<body style="margin:0; padding:24px; font-family:system-ui, sans-serif; color:#111">
  <h1 style="font-size:20px">Thanks for your order, {{.Name}}</h1>
  <p>Order <strong>{{.Order}}</strong> is confirmed.</p>
  <table cellpadding="6" style="border-collapse:collapse">
    {{range .Items}}
    <tr><td>{{.Qty}} x {{.Name}}</td><td align="right">{{.Price}}</td></tr>
    {{end}}
    <tr><td><strong>Total</strong></td><td align="right"><strong>{{.Total}}</strong></td></tr>
  </table>
  <p><a href="{{.URL}}">View your order</a></p>
  {{template "footer" .}}
</body>
</html>

A shared footer, templates/footer.html, that every HTML email pulls in with {{template "footer" .}}:

{{define "footer"}}<p style="color:#666; font-size:12px">Acme Ltd. Reply to this email if anything looks wrong.</p>{{end}}

And the plain-text alternative, templates/receipt.txt:

Thanks for your order, {{.Name}}.

Order {{.Order}} is confirmed.
{{range .Items}}
  {{.Qty}} x {{.Name}}  {{.Price}}{{end}}

Total: {{.Total}}

View your order: {{.URL}}

Acme Ltd. Reply to this email if anything looks wrong.

The styles are inline on purpose. Some mail clients drop or rewrite parts of a <style> block, while style="" attributes and a plain <table> hold up across Gmail, Outlook and Apple Mail. Keep the layout simple: one column, system fonts, widths in a table rather than CSS grid.

The data and the send call

The template’s fields come from a Go struct. {{range .Items}} walks a slice, and inside it {{.Name}} means the item’s name. The program embeds the folder, parses both sets of templates once at start-up, renders them with the same value, and sends:

package main

import (
	"bytes"
	"embed"
	htmltemplate "html/template"
	"log"
	"os"
	texttemplate "text/template"

	"mailcycle.email/go" // package mailcycle
)

//go:embed templates
var templates embed.FS

// Parsed once: a broken template stops the program at start-up, not on an order.
var (
	htmlEmails = htmltemplate.Must(htmltemplate.ParseFS(templates, "templates/*.html"))
	textEmails = texttemplate.Must(texttemplate.ParseFS(templates, "templates/*.txt"))
)

type item struct {
	Name  string
	Qty   int
	Price string
}

type receipt struct {
	Name, Order, Total, URL string
	Items                   []item
}

func main() {
	mc, err := mailcycle.WithAPIKey(os.Getenv("MAILCYCLE_API_KEY"), "", mailcycle.Options{})
	if err != nil {
		log.Fatal(err)
	}

	r := receipt{
		Name:  "Sam",
		Order: "A-1042",
		Total: "£24.00",
		URL:   "https://example.com/orders/A-1042",
		Items: []item{{Name: "Notebook", Qty: 2, Price: "£24.00"}},
	}

	var html, text bytes.Buffer
	if err := htmlEmails.ExecuteTemplate(&html, "receipt.html", r); err != nil {
		log.Fatal(err)
	}
	if err := textEmails.ExecuteTemplate(&text, "receipt.txt", r); err != nil {
		log.Fatal(err)
	}

	sent, err := mc.Messages().Send(mailcycle.Outgoing{
		From:     os.Getenv("MAILCYCLE_FROM"),
		FromName: "Acme orders",
		To:       "sam@example.com",
		Subject:  "Order " + r.Order + " confirmed",
		Text:     text.String(), // the plain-text alternative
		HTML:     html.String(),
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("sent", sent.MessageID)
}

A few details in there:

  • ParseFS names each template by its file name, so you execute "receipt.html", and footer.html’s {{define "footer"}} becomes available to every HTML template parsed with it.
  • Two imports, two aliases. html/template and text/template are both package template, so give them names. Use the HTML one only for the HTML part: text/template escapes nothing, which is right for a .txt body and wrong for markup.
  • //go:embed templates compiles the folder into the binary. A container image or a single binary on a server carries its email templates with it, with no path to get wrong at run time.
  • Render before you send. If ExecuteTemplate fails, on a field name typo for example, nothing has gone out yet, and the error names the template and the line.

When we ran this against a live Mailcycle address, with the customer name set to Sam <test>, the message arrived with both parts. The HTML carried Sam &lt;test&gt; and the item table, and the text part read exactly as receipt.txt lays it out.

Golang HTML email checklist

  • Set Text and HTML on every message, from templates fed the same data.
  • Keep user data in template fields, never in the template source, so html/template escapes it.
  • Use absolute https:// links: a relative link has no page to be relative to in an inbox.
  • Images: host them, or attach them inline with ContentID (step 5) and refer to cid: in the HTML.
  • Send yourself one before customers get it, and look at it in at least two mail apps.

A reusable mailer package in Go

Once a second handler needs to send a receipt, the template parsing and the Outgoing fields want one home. A small mailer package gives every part of the app one method per email, keeps the templates next to the code that renders them, and is easy to fake in tests. This is the shape most Go codebases settle on: a Mailer type that wraps the client.

acme/
  go.mod
  cmd/receipt/main.go
  mailer/
    mailer.go
    mailer_test.go
    templates/
      receipt.html
      footer.html
      receipt.txt

mailer/mailer.go:

// Package mailer sends Acme's email. It wraps the Mailcycle client in one
// type, with HTML and plain-text templates compiled into the binary.
package mailer

import (
	"bytes"
	"embed"
	"fmt"
	htmltemplate "html/template"
	texttemplate "text/template"

	"mailcycle.email/go" // package mailcycle
)

//go:embed templates
var files embed.FS

// Sender is the one SDK method the mailer uses. *mailcycle.Messages satisfies it.
type Sender interface {
	Send(mailcycle.Outgoing) (mailcycle.SendResult, error)
}

// Mailer renders a template pair and sends the result from one address.
type Mailer struct {
	send     Sender
	from     string
	fromName string
	html     *htmltemplate.Template
	text     *texttemplate.Template
}

// New parses every template once, so a broken one fails at start-up.
func New(send Sender, from, fromName string) (*Mailer, error) {
	html, err := htmltemplate.ParseFS(files, "templates/*.html")
	if err != nil {
		return nil, fmt.Errorf("mailer: html templates: %w", err)
	}
	text, err := texttemplate.ParseFS(files, "templates/*.txt")
	if err != nil {
		return nil, fmt.Errorf("mailer: text templates: %w", err)
	}
	return &Mailer{send: send, from: from, fromName: fromName, html: html, text: text}, nil
}

// Email is one message: Template "receipt" renders receipt.html and receipt.txt.
type Email struct {
	To          string
	Subject     string
	Template    string
	Data        any
	Attachments []mailcycle.OutgoingAttachment
}

// Send renders both parts and sends them as one message.
func (m *Mailer) Send(e Email) (mailcycle.SendResult, error) {
	var html, text bytes.Buffer
	if err := m.html.ExecuteTemplate(&html, e.Template+".html", e.Data); err != nil {
		return mailcycle.SendResult{}, fmt.Errorf("mailer: render %s.html: %w", e.Template, err)
	}
	if err := m.text.ExecuteTemplate(&text, e.Template+".txt", e.Data); err != nil {
		return mailcycle.SendResult{}, fmt.Errorf("mailer: render %s.txt: %w", e.Template, err)
	}
	return m.send.Send(mailcycle.Outgoing{
		From:        m.from,
		FromName:    m.fromName,
		To:          e.To,
		Subject:     e.Subject,
		Text:        text.String(),
		HTML:        html.String(),
		Attachments: e.Attachments,
	})
}

// Item is one line on a receipt.
type Item struct {
	Name  string
	Qty   int
	Price string
}

// Receipt is the data receipt.html and receipt.txt expect.
type Receipt struct {
	Name, Order, Total, URL string
	Items                   []Item
}

// Receipt emails an order confirmation.
func (m *Mailer) Receipt(to string, r Receipt) error {
	_, err := m.Send(Email{
		To:       to,
		Subject:  "Order " + r.Order + " confirmed",
		Template: "receipt",
		Data:     r,
	})
	return err
}

Wiring it up in cmd/receipt/main.go is three lines of setup, and every later email is one call:

package main

import (
	"log"
	"os"
	"time"

	"mailcycle.email/go" // package mailcycle

	"example.com/acme/mailer"
)

func main() {
	mc, err := mailcycle.WithAPIKey(os.Getenv("MAILCYCLE_API_KEY"), "", mailcycle.Options{Timeout: 10 * time.Second})
	if err != nil {
		log.Fatal(err)
	}
	m, err := mailer.New(mc.Messages(), os.Getenv("MAILCYCLE_FROM"), "Acme orders")
	if err != nil {
		log.Fatal(err)
	}

	err = m.Receipt("sam@example.com", mailer.Receipt{
		Name:  "Sam",
		Order: "A-1042",
		Total: "£24.00",
		URL:   "https://example.com/orders/A-1042",
		Items: []mailer.Item{{Name: "Notebook", Qty: 2, Price: "£24.00"}},
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("receipt sent")
}

Why it’s built this way:

  • Sender is an interface of one method. mc.Messages() satisfies it in production. A test passes a fake that records what would have gone out, so the templates get tested without a network or a key.
  • One method per email. Receipt, then Welcome, Invite and PasswordChanged as you need them, each with its own data struct. A handler can’t send a receipt with the invite’s fields, because the compiler checks the struct.
  • Send stays exported for one-off messages and attachments: pass an Email with Attachments set, using the fields from step 5.
  • The From address is set once, from configuration, so no handler can send from the wrong address.

The test, mailer/mailer_test.go, checks escaping and the text part in one go:

package mailer

import (
	"strings"
	"testing"

	"mailcycle.email/go" // package mailcycle
)

type fakeSender struct{ sent []mailcycle.Outgoing }

func (f *fakeSender) Send(out mailcycle.Outgoing) (mailcycle.SendResult, error) {
	f.sent = append(f.sent, out)
	return mailcycle.SendResult{MessageID: "<test@example>"}, nil
}

func TestReceipt(t *testing.T) {
	fake := &fakeSender{}
	m, err := New(fake, "receipts@example.com", "Acme")
	if err != nil {
		t.Fatal(err)
	}
	err = m.Receipt("sam@example.com", Receipt{
		Name:  "<b>Sam</b>",
		Order: "A-1042",
		Total: "£24.00",
		URL:   "https://example.com/orders/A-1042",
		Items: []Item{{Name: "Notebook", Qty: 2, Price: "£24.00"}},
	})
	if err != nil {
		t.Fatal(err)
	}
	out := fake.sent[0]
	if !strings.Contains(out.HTML, "&lt;b&gt;Sam&lt;/b&gt;") {
		t.Errorf("HTML did not escape the name: %s", out.HTML)
	}
	if !strings.Contains(out.Text, "2 x Notebook") || out.Subject != "Order A-1042 confirmed" {
		t.Errorf("text part %q, subject %q", out.Text, out.Subject)
	}
}

go test ./mailer passes in about half a second. In a web service, build the Mailer once in main and hand it to your handlers the way step 3 hands them mc.Messages(). If sending should never hold up a request, put m.Receipt behind a queue or a worker goroutine, and give it the retry rules from step 9.

Step 5: Send email with an attachment in Golang

Attachments are raw bytes. You hand the SDK a []byte and it does the base64 encoding, so there’s no MIME multipart to assemble. This example attaches a PDF from disk and shows a logo inline from a file compiled into the binary:

package main

import (
	_ "embed"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"mailcycle.email/go" // package mailcycle
)

//go:embed logo.png
var logo []byte

func main() {
	mc, err := mailcycle.WithAPIKey(os.Getenv("MAILCYCLE_API_KEY"), "", mailcycle.Options{})
	if err != nil {
		log.Fatal(err)
	}

	path := "invoices/A-1042.pdf"
	pdf, err := os.ReadFile(path)
	if err != nil {
		log.Fatal(err)
	}

	_, err = mc.Messages().Send(mailcycle.Outgoing{
		From:    os.Getenv("MAILCYCLE_FROM"),
		To:      "sam@example.com",
		Subject: "Your invoice A-1042",
		Text:    "Your invoice is attached.",
		HTML:    `<img src="cid:logo" alt="Acme" width="120"><p>Your invoice is attached.</p>`,
		Attachments: []mailcycle.OutgoingAttachment{
			{
				Filename: filepath.Base(path),
				MimeType: http.DetectContentType(pdf), // "application/pdf"
				Content:  pdf,
			},
			{
				Filename:  "logo.png",
				MimeType:  "image/png",
				Content:   logo,
				ContentID: "logo", // shown where the HTML says cid:logo
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
}
  • ContentID makes a file inline: it appears where the HTML has cid: and the same id, instead of as a download.
  • MimeType defaults to application/octet-stream. http.DetectContentType sniffs common types from the first 512 bytes; for formats it doesn’t know, set the type yourself.
  • Filename is what the recipient saves. Use filepath.Base so a server path never leaks into the email.
  • Program and script files such as .exe, .bat, .js and .ps1 are refused with attachment_blocked. A message can carry up to ten files, 3.5 MB between them, and the SDK refuses an oversized set before it makes a request.

If you generate the PDF in memory, with a library writing to a bytes.Buffer, pass buf.Bytes() as Content and skip the disk entirely.

Step 6: The same send as a raw HTTP call (cURL)

Everything above is one endpoint, POST /messages/send. Here’s the plain-text send as cURL, which is handy for checking a key or reproducing a problem outside Go:

curl https://api.mailcycle.email/messages/send \
  -H "Authorization: Bearer $MAILCYCLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "receipts-x7k2@example-pool.email",
    "to": "someone@example.com",
    "subject": "Hello",
    "text": "Plain text body"
  }'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }

The SDK’s SendResult carries the same two values: MessageID is the Message-ID header the mail went out with, and SentCopyID is the copy filed in the address’s Sent folder, sealed like received mail. Attachments go in an attachments array with base64 content, which is exactly what OutgoingAttachment produces. The field-by-field rules are in Sending mail.

You could call this with net/http and encoding/json yourself. The SDK earns its place on the receiving side: reading mail means decrypting it with keys derived from your phrase, which is real cryptography you don’t want to rewrite.

Step 7: Wait for a reply and answer in the same thread

Send-only email APIs stop at the send. With Mailcycle, the address you send from is also an inbox, so a reply comes back to the same place, and your Go code can read it. That makes flows like “email the customer, wait for YES, confirm” a single function:

package main

import (
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"mailcycle.email/go" // package mailcycle
)

func main() {
	mc, err := mailcycle.WithAPIKey(
		os.Getenv("MAILCYCLE_API_KEY"),
		os.Getenv("MAILCYCLE_PHRASE"), // needed to open the reply
		mailcycle.Options{},
	)
	if err != nil {
		log.Fatal(err)
	}

	from := os.Getenv("MAILCYCLE_FROM")
	addressID, err := addressIDFor(mc, from)
	if err != nil {
		log.Fatal(err)
	}
	customer := "sam@example.com"

	since := time.Now() // take the time before sending
	if _, err := mc.Messages().Send(mailcycle.Outgoing{
		From:    from,
		To:      customer,
		Subject: "Can we book your delivery for Thursday?",
		Text:    "Reply YES to confirm, or suggest another day.",
	}); err != nil {
		log.Fatal(err)
	}

	reply, err := mc.Messages().WaitFor(mailcycle.WaitOptions{
		AddressID: addressID,
		From:      customer,
		Timeout:   10 * time.Minute,
		Since:     since,
	})
	if mailcycle.ErrorCode(err) == "timeout" {
		log.Fatal("no reply in 10 minutes")
	}
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s replied: %s\n", reply.FromAddress, reply.Text)

	// Answer in the same thread.
	if _, err := mc.Messages().Send(mailcycle.Outgoing{
		From:      from,
		To:        reply.ReplyTo,
		Subject:   re(reply.Subject),
		Text:      "Booked. See you Thursday.",
		InReplyTo: &reply, // sets inReplyTo and the Message-ID header
	}); err != nil {
		log.Fatal(err)
	}
}

// addressIDFor finds the ibx_... id of one of the account's addresses.
func addressIDFor(mc *mailcycle.Client, email string) (string, error) {
	addresses, err := mc.Addresses().List()
	if err != nil {
		return "", err
	}
	for _, a := range addresses {
		if strings.EqualFold(a.EmailAddress, email) {
			return a.ID, nil
		}
	}
	return "", fmt.Errorf("%s is not an address on this account", email)
}

func re(subject string) string {
	if strings.HasPrefix(strings.ToLower(subject), "re:") {
		return subject
	}
	return "Re: " + subject
}

How the pieces fit:

  • WaitFor blocks until a matching message arrives, then returns it already decrypted. It listens on the event stream and falls back to checking the address every five seconds where the stream can’t open, which is why AddressID matters.
  • Since closes the race. Mail received from Since onwards counts, even if it landed before WaitFor was listening. It defaults to the moment you call WaitFor, so take time.Now() before the send, or a quick reply could slip past.
  • From and Subject filter by case-insensitive substring, against the sender’s name and address and the subject.
  • A timeout is an error, not an empty message. It comes back as an *APIError with Code == "timeout", so ErrorCode tells it apart from a real failure.
  • Threading. InReplyTo: &reply sends both the Mailcycle message id and the original’s Message-ID header, so the answer sits under the customer’s reply in Gmail, Outlook or Apple Mail. Send it To: reply.ReplyTo, which is the sender’s Reply-To if they set one and their From otherwise.

A blocked goroutine is fine in a CLI, a worker or a test. In a web server, don’t hold a request open for ten minutes: run the wait in a background job, or use a webhook instead.

Step 8: Receive replies in a Go webhook handler

For a long-running service, let Mailcycle call you. A webhook posts a signed message.received event to your URL the moment mail arrives. Events carry ids, never content, so your handler fetches the message and decrypts it locally. Create the webhook in the app under API, on the Webhooks tab, and keep its whsec_ secret.

package main

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"mailcycle.email/go" // package mailcycle
)

type event struct {
	Type    string `json:"type"`
	Payload struct {
		MessageID string `json:"messageId"`
		InboxID   string `json:"inboxId"`
	} `json:"payload"`
}

func main() {
	mc, err := mailcycle.WithAPIKey(
		os.Getenv("MAILCYCLE_API_KEY"),
		os.Getenv("MAILCYCLE_PHRASE"),
		mailcycle.Options{Timeout: 10 * time.Second},
	)
	if err != nil {
		log.Fatal(err)
	}
	secret := os.Getenv("MAILCYCLE_WEBHOOK_SECRET") // whsec_...

	mux := http.NewServeMux()
	mux.HandleFunc("POST /hooks/mailcycle", func(w http.ResponseWriter, r *http.Request) {
		raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10))
		if err != nil {
			http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
			return
		}
		if !mailcycle.VerifyWebhookSignature(secret, raw, r.Header.Get("Mailcycle-Signature")) {
			http.Error(w, "bad signature", http.StatusUnauthorized)
			return
		}

		var e event
		if err := json.Unmarshal(raw, &e); err != nil {
			http.Error(w, "bad body", http.StatusBadRequest)
			return
		}
		// Answer inside 10 seconds; do the work after.
		w.WriteHeader(http.StatusNoContent)

		if e.Type == "message.received" {
			go handleReply(mc, r.Header.Get("Mailcycle-Event-Id"), e.Payload.MessageID)
		}
	})

	srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	log.Fatal(srv.ListenAndServe())
}

func handleReply(mc *mailcycle.Client, eventID, messageID string) {
	// Deliveries can repeat: skip eventID if you have seen it before.
	message, err := mc.Messages().Get(messageID)
	if err != nil {
		log.Printf("event %s: fetch %s: %v", eventID, messageID, err)
		return
	}
	if !message.Opened {
		log.Printf("event %s: %s did not open; check MAILCYCLE_PHRASE", eventID, messageID)
		return
	}
	if strings.HasPrefix(strings.ToUpper(strings.TrimSpace(message.Text)), "YES") {
		log.Printf("%s confirmed", message.FromAddress)
	}
}

The rules that matter:

  • Verify the raw bytes. VerifyWebhookSignature checks the HMAC over the body exactly as it arrived and refuses a timestamp older than five minutes. Read the body with io.ReadAll before any JSON decoding; a re-encoded body is a different string and won’t verify.
  • Answer fast. Mailcycle wants a 2xx within 10 seconds and retries failures for about a day and a half, so reply first and do the slow work after. A goroutine is fine for a sketch; in production, push the event onto a queue you already run.
  • Deduplicate. Events can arrive more than once and out of order. Mailcycle-Event-Id is the same on every attempt, so store it and skip repeats.
  • Opened == false isn’t an error. A message that won’t open, because the client has no phrase or the wrong one, comes back with empty content rather than failing, so one bad message never hides the rest.

When you render a received message, use message.SafeHTML, not message.HTML: it has remote images and other trackers removed, the way the Mailcycle apps show mail. Reading mail covers folders, paging and attachments.

Step 9: Handle errors by code

Every API failure is an *APIError with the HTTP Status, a stable Code and a human Message. Branch on the code, never the message: mailcycle.ErrorCode(err) pulls it out, and returns "" for anything that isn’t an APIError. Use errors.As when you need the status too, as the handler in step 3 did.

Here’s a send wrapper that retries only what’s safe to retry:

package errs

import (
	"errors"
	"fmt"
	"time"

	"mailcycle.email/go" // package mailcycle
)

var (
	// ErrRejected is a send that will fail the same way every time.
	ErrRejected = errors.New("send rejected")
	// ErrTomorrow is a send to queue until 00:00 UTC.
	ErrTomorrow = errors.New("sending stopped for today")
)

func sendWithRetry(m *mailcycle.Messages, out mailcycle.Outgoing) (mailcycle.SendResult, error) {
	delay := 2 * time.Second
	for attempt := 1; ; attempt++ {
		sent, err := m.Send(out)
		if err == nil {
			return sent, nil
		}

		switch mailcycle.ErrorCode(err) {
		case "rate_limited", "send_failed", "internal", "provider_error", "maintenance":
			// Nothing went out. Worth another go after a pause.
		case "daily_send_limit", "sending_paused":
			return sent, fmt.Errorf("%w: %w", ErrTomorrow, err)
		case "plan_required":
			return sent, fmt.Errorf("%w: sending with an API key needs Scale or above: %w", ErrRejected, err)
		case "not_your_address", "invalid_address", "address_paused", "address_suspended",
			"domain_not_sending", "attachment_blocked", "attachments_too_large",
			"message_too_large", "too_many_attachments":
			return sent, fmt.Errorf("%w: %w", ErrRejected, err)
		default:
			// network_error and anything unknown: the request may have
			// reached the API, so a blind resend could send it twice.
			return sent, err
		}

		if attempt == 4 {
			return sent, err
		}
		time.Sleep(delay)
		delay *= 2
	}
}

Callers can then use errors.Is(err, ErrTomorrow) to park a message in a queue, and errors.Is(err, ErrRejected) to surface a bug, while errors.As still reaches the underlying *mailcycle.APIError through the double %w.

What the codes mean for sending:

Code Status What to do
rate_limited 429 Too many requests in a short window. Back off and retry.
daily_send_limit 429 The plan’s mail for today is sent. Queue it; sending resumes at 00:00 UTC.
plan_required 403 The key’s account is below Scale. Upgrade or start the trial.
not_your_address 403 From isn’t an address on this account.
invalid_address 400 To isn’t one plain address. Parse it with net/mail first.
domain_not_sending 409 Sending on your own domain isn’t on yet; it usually follows receiving within minutes.
attachment_blocked, attachments_too_large, message_too_large, too_many_attachments 400, 413 Fix the attachments. Nothing was sent.
send_failed, internal, provider_error, maintenance 5xx Retry with backoff.
network_error 0 The SDK never got an answer, including when Options.Timeout ran out. The mail may or may not have gone.
timeout 0 Only from WaitFor: nothing matching arrived in time.

A 429 from the API also carries a Retry-After header. The SDK’s error doesn’t expose headers, so exponential backoff, as above, is the practical approach; the message text says how long to wait in words if you want to log it. The full picture is in the rate limits reference and the errors reference.

Step 10: Test Go email code without sending email

Go’s implicit interfaces make the sender easy to fake. Depend on the one method you use, and *mailcycle.Messages satisfies it without any adapter:

package signup

import "mailcycle.email/go" // package mailcycle

// Mailer is the one method signup needs. *mailcycle.Messages satisfies it.
type Mailer interface {
	Send(mailcycle.Outgoing) (mailcycle.SendResult, error)
}

type Service struct {
	Mail Mailer
	From string
}

func (s *Service) Welcome(email, name string) error {
	_, err := s.Mail.Send(mailcycle.Outgoing{
		From:    s.From,
		To:      email,
		Subject: "Welcome to Acme, " + name,
		Text:    "Your account is ready.",
	})
	return err
}

In production, pass mc.Messages(). In tests, pass a fake, or point a real client at an httptest.Server with Options.APIURL to check how your code handles an API error:

package signup

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"mailcycle.email/go" // package mailcycle
)

type fakeMailer struct{ sent []mailcycle.Outgoing }

func (f *fakeMailer) Send(out mailcycle.Outgoing) (mailcycle.SendResult, error) {
	f.sent = append(f.sent, out)
	return mailcycle.SendResult{MessageID: "<test@example>"}, nil
}

func TestWelcome(t *testing.T) {
	fake := &fakeMailer{}
	s := &Service{Mail: fake, From: "hello@example.com"}

	if err := s.Welcome("sam@example.com", "Sam"); err != nil {
		t.Fatal(err)
	}
	if len(fake.sent) != 1 || fake.sent[0].To != "sam@example.com" {
		t.Fatalf("sent %+v", fake.sent)
	}
}

func TestWelcomeRateLimited(t *testing.T) {
	api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusTooManyRequests)
		w.Write([]byte(`{"code":"rate_limited","message":"Try again in a minute."}`))
	}))
	defer api.Close()

	mc, err := mailcycle.WithAPIKey("mak_test", "", mailcycle.Options{APIURL: api.URL})
	if err != nil {
		t.Fatal(err)
	}
	s := &Service{Mail: mc.Messages(), From: "hello@example.com"}

	err = s.Welcome("sam@example.com", "Sam")
	if got := mailcycle.ErrorCode(err); got != "rate_limited" {
		t.Fatalf("ErrorCode = %q, want rate_limited", got)
	}
}

go test ./... runs both in well under a second, with no key and no network. For end-to-end tests of a real sign-up flow, create a fresh address at the start of the test, drive your app, and WaitFor the email it sends; the Go SDK page has that pattern.

net/smtp vs gomail vs an email API in Go

Go’s standard library has net/smtp, and the package documentation is candid about it: “The smtp package is frozen and is not accepting new features. Some external packages provide more functionality.” It still works. Here’s the plain-text send from the quick answer, written with it:

package main

import (
	"log"
	"net/smtp"
	"os"
)

func main() {
	host := "smtp.example.com"
	auth := smtp.PlainAuth("", os.Getenv("SMTP_USER"), os.Getenv("SMTP_PASS"), host)

	msg := []byte("From: hello@example.com\r\n" +
		"To: sam@example.com\r\n" +
		"Subject: Hello from Go\r\n" +
		"MIME-Version: 1.0\r\n" +
		"Content-Type: text/plain; charset=UTF-8\r\n" +
		"\r\n" +
		"Sent with net/smtp.\r\n")

	err := smtp.SendMail(host+":587", auth, "hello@example.com", []string{"sam@example.com"}, msg)
	if err != nil {
		log.Fatal(err)
	}
}

You supply the server, the port, and the credentials, and you write the message headers yourself. SendMail upgrades to TLS when the server offers it, and PlainAuth only sends credentials over TLS or to localhost. HTML alternatives and attachments mean building multipart/alternative and multipart/mixed bodies by hand, or with mime/multipart. Gomail-style libraries do that MIME work for you, with a friendlier message builder, and still dial an SMTP server you provide.

net/smtp Gomail-style library Mailcycle Go SDK
Transport SMTP to a server you supply SMTP to a server you supply HTTPS to one API
Credentials SMTP username and password SMTP username and password One mak_ API key
Ports and TLS STARTTLS on 587 via SendMail; your own tls.Dial for 465 Configured on the dialer Ordinary HTTPS on 443
HTML and attachments Hand-built MIME Built for you Struct fields; bytes in, encoding done
Threading a reply Set In-Reply-To and References headers yourself Set headers yourself InReplyTo: &message
Receiving replies Not covered; no IMAP in the standard library Not covered Same address: WaitFor, All, webhooks
Errors SMTP reply codes, as *textproto.Error The SMTP server’s replies *APIError with a stable Code
Stored mail Depends on your provider Depends on your provider Encrypted, keys derived from your phrase on your machine

An email API pays off when you’d rather not operate mail infrastructure, want errors you can switch on, or need the replies too: an AI agent answering support mail, a booking flow waiting for “YES”, a test suite reading sign-in codes.

Golang send email with Gmail: moving to an email API

Many Go projects start by sending through a Gmail account, and “golang send email gmail” is a common search. There are two usual routes. The first is net/smtp pointed at smtp.gmail.com on port 587, signed in with an app password, which Google offers on accounts with 2-Step Verification. The second is the Gmail API: an OAuth client in Google Cloud, a consent screen, a stored refresh token, and a call to users.messages.send with the whole message built as RFC 2822 text and base64url-encoded.

Both tie your app’s mail to a personal Google sign-in. When the mail is your product’s (sign-in codes, receipts, alerts), it reads better from an address of its own, and the code gets shorter. With the Mailcycle Go SDK the move looks like this:

  1. Create a sending address in the app, or with mc.Addresses().Create as in step 2. On Scale you can send from your own domain, so codes come from signin@yourcompany.com.
  2. Create an API key and put it in MAILCYCLE_API_KEY, with the address in MAILCYCLE_FROM.
  3. Swap the body of your send helper and keep its signature, so no caller changes.
  4. Remove the old secret from your environment, and revoke the app password or OAuth client in your Google account once nothing uses it.

Most Gmail-era code has a helper like sendMail(to, subject, body string) error that builds headers and calls smtp.SendMail. Here it is with the SDK inside, so every call site stays as it was:

package notify

import (
	"os"
	"time"

	"mailcycle.email/go" // package mailcycle
)

var messages *mailcycle.Messages

// Init builds the client once, at start-up.
func Init() error {
	mc, err := mailcycle.WithAPIKey(os.Getenv("MAILCYCLE_API_KEY"), "", mailcycle.Options{Timeout: 10 * time.Second})
	if err != nil {
		return err
	}
	messages = mc.Messages()
	return nil
}

// sendMail keeps the signature of the old Gmail SMTP helper.
func sendMail(to, subject, body string) error {
	_, err := messages.Send(mailcycle.Outgoing{
		From:    os.Getenv("MAILCYCLE_FROM"),
		To:      to,
		Subject: subject,
		Text:    body,
	})
	return err
}

What you gain in the swap:

  • One API key in place of an app password or an OAuth token to refresh.
  • No MIME to build. The Gmail API wants a base64url RFC 2822 message; here HTML, text and attachments are struct fields.
  • Replies in the same place. The address you send from is an inbox, so customers can answer, and your Go code reads the answer with WaitFor or a webhook (steps 7 and 8).
  • Threads that hold together in Gmail. Recipients on Gmail see your replies grouped in one conversation when you set InReplyTo, because the SDK sends the original’s Message-ID and the reply goes out with In-Reply-To and References headers.

Your personal Gmail stays your personal inbox. The SDK talks only to the Mailcycle API.

Using Go email in AI agents

If the code sending mail is an agent rather than a handler, the same address-of-its-own model applies. Mailcycle agents get their own addresses, start reply-only, and connect over MCP to Claude Code, Cursor or any other MCP client; our Claude Code walkthrough shows it end to end, and the agents page explains the model. If your agent is a Go program, the SDK in this guide is the direct route: WaitFor the message, decide, Send with InReplyTo.

Next steps for sending email in Golang

You’ve sent plain, HTML-template and attachment email from Go, wrapped it in a mailer package, served it from a net/http handler with sane timeouts, waited for a reply and answered it in the thread, received mail on a webhook, and handled errors by code. From here:

FAQ

How do I send an email in Go without SMTP?

Run go get mailcycle.email/go, create a client with mailcycle.WithAPIKey(os.Getenv("MAILCYCLE_API_KEY"), "", mailcycle.Options{}), and call mc.Messages().Send(mailcycle.Outgoing{From, To, Subject, Text}). It is one HTTPS request: no SMTP host, port, TLS settings or MIME building. From must be an address on your Mailcycle account.

Is net/smtp deprecated in Go?

No, but it is frozen. The package documentation says it "is frozen and is not accepting new features" and points to external packages for more. It still works for sending through an SMTP server you have credentials for; it has no MIME helpers for HTML or attachments, and the standard library has no IMAP client for receiving.

How do I send an email with an attachment in Golang?

Read the file into a []byte with os.ReadFile or //go:embed, and add a mailcycle.OutgoingAttachment{Filename, MimeType, Content} to Outgoing.Attachments. The SDK base64-encodes it for you. A message carries up to ten files, 3.5 MB between them, and program or script files such as .exe and .js are refused.

How do I send HTML email in Golang?

Render the body with html/template, which escapes your data, and pass the result as Outgoing.HTML. Always set Outgoing.Text too: the API requires a plain-text part, and mail clients that don't show HTML use it. Inline images use ContentID on an attachment and cid: in the HTML.

How do I send email with an HTML template in Golang?

Keep the template in a file such as templates/receipt.html, compile it into the binary with //go:embed, and parse it once with html/template.ParseFS. For each email, call ExecuteTemplate with your data into a bytes.Buffer and pass buf.String() as Outgoing.HTML. Render a matching receipt.txt with text/template for Outgoing.Text, so every message carries a plain-text alternative.

Does the Go SDK send a plain-text alternative with HTML email?

Yes. Set both Text and HTML on mailcycle.Outgoing and the message goes out with both parts, so each mail client shows the one it prefers. Text is required on every send, which means a plain-text alternative is always there.

How do I write a reusable mailer in Golang?

Make a small mailer package: a Mailer struct holding the SDK's *mailcycle.Messages (behind a one-method interface), the From address and the parsed templates, with one method per email, such as Receipt(to, data). Handlers call m.Receipt(...), tests pass a fake sender, and the templates live in one place.

What is the best Golang mail package for sending email with an API?

For an API rather than SMTP, mailcycle.email/go is one go get: Messages().Send takes a plain struct with text, HTML, attachments and an optional reply-to message, and errors carry a stable code you can switch on. The same package reads the replies, so one Go email library covers both directions.

Can I send email from Go with Gmail?

Gmail offers two routes: net/smtp to smtp.gmail.com on port 587 with an app password, or the Gmail API with an OAuth client. With Mailcycle, your Go code sends from an address on your Mailcycle account, or your own domain on Scale, with one API key, and mail to Gmail recipients threads in Gmail when you set InReplyTo. The SDK talks only to the Mailcycle API, so your Google account stays out of your app.

Does the Mailcycle Go SDK take a context.Context?

No. Its methods are synchronous and each HTTP request is bounded by Options.Timeout, 30 seconds by default. In a handler, set that timeout below your server's WriteTimeout, and check r.Context().Err() before you send so a client that has already gone away doesn't trigger an email.

How do I reply to an email in the same thread from Go?

Pass the message you are answering as InReplyTo: &message, send To: message.ReplyTo, and prefix the subject with Re:. The SDK sends both the Mailcycle message id and the original's Message-ID header, so the reply threads in the recipient's mail client. See Sending mail.

Can I receive email in Go with the same SDK?

Yes. Replies land in the same address you sent from. mc.Messages().WaitFor() blocks until a matching message arrives, mc.Messages().All() lists an address's mail, and a webhook can tell your server the moment one lands. Reading needs your recovery phrase, because mail is decrypted on your machine.

Which Mailcycle plan do I need to send email with an API key?

Scale or above, or the free 7-day Scale trial, which needs no card. API keys exist from Operator, but a key on Operator gets 403 plan_required from the send endpoint. See pricing.

How do I handle rate limit errors when sending email from Go?

Branch on mailcycle.ErrorCode(err). rate_limited is worth a retry after a pause; daily_send_limit means nothing more goes out until 00:00 UTC, so queue the mail rather than loop. The numbers are in the rate limits reference.

What Go version does the Mailcycle SDK need?

Go 1.26 or later. The module path is mailcycle.email/go and the package name is mailcycle, so you import it as "mailcycle.email/go" and call mailcycle.WithAPIKey.

Send email from any language