Go’s standard library covers both ways to send email. net/http and encoding/json can call an email API in a dozen lines, and net/smtp can talk to an SMTP server. The API route is the simpler of the two because you do not have to build MIME messages by hand.
Option 1: an email API with net/http
This example sends one email through Mailcandor’s REST API and returns its id:
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
type Email struct {
From string `json:"from"`
To []string `json:"to"`
Subject string `json:"subject"`
HTML string `json:"html,omitempty"`
Text string `json:"text,omitempty"`
ReplyTo string `json:"reply_to,omitempty"`
}
type apiError struct {
Error struct {
Type string `json:"type"`
Message string `json:"message"`
} `json:"error"`
}
var client = &http.Client{Timeout: 10 * time.Second}
func sendEmail(ctx context.Context, e Email, idempotencyKey string) (string, error) {
body, err := json.Marshal(e)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://api.mailcandor.com/v1/emails", bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MAILCANDOR_KEY"))
req.Header.Set("Content-Type", "application/json")
if idempotencyKey != "" {
req.Header.Set("Idempotency-Key", idempotencyKey)
}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted {
var ae apiError
if err := json.NewDecoder(resp.Body).Decode(&ae); err != nil {
return "", fmt.Errorf("email API returned %s", resp.Status)
}
return "", fmt.Errorf("%s: %s", ae.Error.Type, ae.Error.Message)
}
var out struct {
ID string `json:"id"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return "", err
}
return out.ID, nil
}
func main() {
id, err := sendEmail(context.Background(), Email{
From: "Acme <hello@acme.com>",
To: []string{"sam@example.com"},
Subject: "Your login code",
HTML: "<p>Your code is <b>481 203</b></p>",
Text: "Your code is 481 203",
}, "login-code-sam-481203")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("queued", id)
}
A few details worth keeping:
- Set a client timeout.
http.DefaultClienthas none, so a stalled connection would hang forever. - Reuse one
http.Client. It pools connections, so later emails skip the TLS handshake. - Pass an idempotency key. If you retry after a timeout, the API returns the first response instead of sending again.
The API answers 202 Accepted as soon as the email is queued. Delivery and bounce events come later as webhooks, which a normal net/http handler can receive.
Attachments go in the same JSON as an attachments array of objects with filename and base64 content; encoding/base64 produces the string with base64.StdEncoding.EncodeToString(data).
Option 2: net/smtp with STARTTLS
smtp.SendMail connects, upgrades to TLS with STARTTLS if the server offers it, authenticates and sends. You supply the raw message, headers included:
package main
import (
"fmt"
"net/smtp"
"os"
"strings"
)
func main() {
host := "smtp.mailcandor.com"
auth := smtp.PlainAuth("", "mailcandor", os.Getenv("MAILCANDOR_KEY"), host)
from := "hello@acme.com"
to := []string{"sam@example.com"}
msg := strings.Join([]string{
"From: Acme <hello@acme.com>",
"To: sam@example.com",
"Subject: Your login code",
"MIME-Version: 1.0",
"Content-Type: text/html; charset=UTF-8",
"",
"<p>Your code is <b>481 203</b></p>",
}, "\r\n")
if err := smtp.SendMail(host+":587", auth, from, to, []byte(msg)); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Things to know about net/smtp:
- Lines end in
\r\n, and a blank line separates headers from the body, as SMTP requires. PlainAuthonly sends the password over TLS (or to localhost). On port 587 that works becauseSendMailupgrades first. If the server does not offer STARTTLS, you get an error rather than a leaked password.- Port 465 needs more code.
SendMaildoes not do implicit TLS. Open the connection withtls.Dial("tcp", host+":465", &tls.Config{ServerName: host}), pass it tosmtp.NewClient, then callAuth,Mail,RcptandDatayourself. - The package is frozen. It gets fixes but no new features. Building a message with both HTML and text parts, or with attachments, means writing MIME by hand with
mime/multipart.
For those cases, a maintained library is easier. go-mail is a popular choice: it builds multipart messages, handles attachments, and supports both port 465 and 587. The SMTP ports guide explains the difference between the two ports.
Sending from a web handler
Inside an HTTP handler, pass the request context so the send is cancelled if the client goes away:
func signupHandler(w http.ResponseWriter, r *http.Request) {
// ... create the user ...
if _, err := sendEmail(r.Context(), welcomeEmail(user), "welcome-"+user.ID); err != nil {
log.Printf("welcome email failed: %v", err)
}
w.WriteHeader(http.StatusCreated)
}
For emails that must not be lost, such as receipts, write the job to a queue or database table and send from a worker that retries with the same idempotency key.
Common errors
535 authentication errors mean wrong credentials. x509: certificate errors usually mean ServerName in your tls.Config does not match the host. A 401 or other 4xx from the API comes with a JSON error whose message says which field to fix.
Which should you choose?
| Email API (net/http) | net/smtp | |
|---|---|---|
| Packages | Standard library | Standard library |
| HTML plus text, attachments | JSON fields | Hand-built MIME, or a library |
| Port 465 | Not relevant (HTTPS) | Manual TLS setup |
| Safe retries | Idempotency keys | Not built in |
| Delivery events | Webhooks per email id | Usually none |
For new Go services, the API is less code and fewer edge cases. To try the same request from the command line first, see the cURL guide.
Before you send: verify your domain
The domain in your From header needs SPF, DKIM and DMARC records, or receiving servers will filter your mail. Add the domain with your provider and publish the records it gives you. The SPF, DKIM and DMARC guide explains each one.