Documentation
¶
Overview ¶
Package onemailer sends transactional email over plain SMTP: password resets, verification links, invites. It speaks SMTP to any provider (Amazon SES, Postmark, SendGrid, Resend, …) and to a development catcher such as Mailpit, so going to production is a change of configuration only. See the README for the settings and the go-live checklist.
The pieces: LoadConfig reads {PREFIX}MAIL_* / {PREFIX}SMTP_* settings and refuses inconsistent ones; SMTPSender delivers one Message with the configured TLS mode (certificates always verified); Queue delivers off the request path with retries and logs outcomes without bodies, links or recipients; mailtest is an in-process SMTP server for tests. NewSender gives a sender that delivers nothing when mail is off, and IsPermanent tells a failure worth retrying from one that is not.
Index ¶
- Constants
- Variables
- func IsLoopback(host string) bool
- func IsPermanent(err error) bool
- func Lifetime(d time.Duration) string
- func Permanent(err error) error
- func SMTPCode(err error) int
- type Attachment
- type Config
- type LoadOption
- type Message
- type Outcome
- type Queue
- type QueueConfig
- type Result
- type SMTPSender
- type Sender
Examples ¶
Constants ¶
const ( ProviderNone = "none" ProviderSMTP = "smtp" )
Providers ({PREFIX}MAIL_PROVIDER).
const ( TLSStartTLS = "starttls" TLSImplicit = "tls" TLSNone = "none" )
TLS modes ({PREFIX}SMTP_TLS).
const ( ReasonQueueFull = "queue_full" // Enqueue found the queue full ReasonShutdown = "shutdown" // the queue closed before delivery ReasonSMTPFailed = "smtp_failed" // every try failed ReasonRejected = "rejected" // a permanent failure; not retried ReasonMailOff = "mail_off" // the sender is off (NewSender with provider none) )
Reasons a message is not sent (Result.Reason, and "reason" in the logs).
Variables ¶
DefaultDelays is the retry schedule: at once, then after 10 s, 1 min and 5 min.
var ErrHeaderInjection = errors.New("onemailer: a header value contains a line break")
ErrHeaderInjection is returned for a header value holding CR or LF.
var ErrMailOff = errors.New("onemailer: mail is off (MAIL_PROVIDER=none)")
ErrMailOff is returned by the sender NewSender gives for provider none. Queue logs it as reason=mail_off, not as a failure.
var ErrPermanent = errors.New("onemailer: permanent failure")
ErrPermanent matches (with errors.Is) a failure that sending again cannot fix: an invalid message, a configuration the server refuses, or an SMTP 5xx reply. Queue does not retry these.
Functions ¶
func IsLoopback ¶
IsLoopback reports whether host is localhost or a loopback IP address.
func IsPermanent ¶ added in v0.2.0
IsPermanent reports whether retrying err is pointless: it was marked with Permanent, or it carries an SMTP 5xx reply (bad recipient, refused login).
Example ¶
Sending synchronously, from a job system that retries on its own.
package main
import (
"context"
"errors"
"github.com/kararnab/onemailer"
)
func main() {
var sender onemailer.Sender // from NewSender
err := sender.Send(context.Background(), onemailer.Message{To: "ada@example.org", Subject: "Hi", Text: "Hi"})
switch {
case err == nil:
case errors.Is(err, onemailer.ErrMailOff):
// mail is off: nothing to do
case onemailer.IsPermanent(err):
// bad address, refused login (SMTP 5xx): retrying will not help
default:
// connection trouble or SMTP 4xx: let the job system retry
}
}
Output:
func Lifetime ¶
Lifetime words a link lifetime for email copy: whole hours when it is a whole number of hours ("1 hour", "48 hours"), otherwise whole minutes, rounded down ("30 minutes", "90 minutes"), never less than a minute.
Example ¶
package main
import (
"fmt"
"time"
"github.com/kararnab/onemailer"
)
func main() {
fmt.Println(onemailer.Lifetime(time.Hour))
fmt.Println(onemailer.Lifetime(48 * time.Hour))
fmt.Println(onemailer.Lifetime(90 * time.Minute))
}
Output: 1 hour 48 hours 90 minutes
Types ¶
type Attachment ¶ added in v0.2.0
type Attachment struct {
Filename string
// ContentType is the media type, such as "application/pdf"; when
// empty it is guessed from the file name's extension.
ContentType string
Data []byte
}
Attachment is one file sent with a message.
type Config ¶
type Config struct {
Provider string
PublicURL string // the web origin links point at; "" when unset
From *mail.Address
ReplyTo *mail.Address // optional ({PREFIX}MAIL_REPLY_TO)
Host string
Port int
TLS string
Username string
// AllowPlainHost is the one non-loopback host that may receive plain
// SMTP ({PREFIX}SMTP_ALLOW_PLAIN_HOST): a development catcher on a
// container network, such as Mailpit at "mailpit".
AllowPlainHost string
// Prefix is the environment-variable prefix the configuration was
// loaded with (for example "LIBRARYZ_"); errors name variables with it.
Prefix string
// contains filtered or unexported fields
}
Config is the mail configuration. Its String method never prints the password.
func LoadConfig ¶
LoadConfig reads the mail settings from the environment, each variable named with prefix (for example "LIBRARYZ_"):
{P}MAIL_PROVIDER none (default) or smtp
{P}PUBLIC_URL absolute http(s) origin links point at; required with smtp
(unless OptionalPublicURL is passed);
http only to localhost or when {P}ENV=development
{P}MAIL_FROM sender, "App <accounts@example.org>"; required with smtp
{P}MAIL_REPLY_TO optional reply address
{P}SMTP_HOST required with smtp
{P}SMTP_PORT default 587
{P}SMTP_TLS starttls (default), tls (implicit, usually 465) or none
{P}SMTP_ALLOW_PLAIN_HOST the one non-loopback host allowed with none (dev catcher)
{P}SMTP_USERNAME login, when the server requires one
{P}SMTP_PASSWORD or {P}SMTP_PASSWORD_FILE (preferred); at most one
Every error names its variable; none contains the password.
Example ¶
The environment of a service whose variables start with MYAPP_.
package main
import (
"fmt"
"log"
"github.com/kararnab/onemailer"
)
func main() {
env := map[string]string{
"MYAPP_MAIL_PROVIDER": "smtp",
"MYAPP_PUBLIC_URL": "https://app.example.org",
"MYAPP_MAIL_FROM": "My App <accounts@example.org>",
"MYAPP_SMTP_HOST": "smtp.sendgrid.net",
"MYAPP_SMTP_USERNAME": "apikey",
"MYAPP_SMTP_PASSWORD": "not-printed",
}
cfg, err := onemailer.LoadConfig(func(k string) string { return env[k] }, "MYAPP_")
if err != nil {
log.Fatal(err)
}
fmt.Println(cfg)
// A mistake names its variable.
env["MYAPP_SMTP_TLS"] = "ssl"
_, err = onemailer.LoadConfig(func(k string) string { return env[k] }, "MYAPP_")
fmt.Println(err)
}
Output: smtp smtp.sendgrid.net:587 (starttls, login apikey), from "My App" <accounts@example.org> MYAPP_SMTP_TLS must be starttls, tls or none, got "ssl"
func (Config) WithPassword ¶ added in v0.2.0
WithPassword returns c with the SMTP password set, for a Config built in code rather than by LoadConfig (flags, a config file, a secret manager). Username must be set too.
Example ¶
Settings from somewhere other than the environment: a config file, flags, a secret manager.
package main
import (
"log"
"net/mail"
"github.com/kararnab/onemailer"
)
func main() {
from, _ := mail.ParseAddress("My App <accounts@example.org>")
cfg := onemailer.Config{
Provider: onemailer.ProviderSMTP,
From: from,
Host: "smtp.postmarkapp.com", // port 587 and starttls by default
Username: "server-token",
}.WithPassword("server-token")
if _, err := onemailer.NewSMTPSender(cfg); err != nil {
log.Fatal(err)
}
}
Output:
type LoadOption ¶ added in v0.2.0
type LoadOption func(*loadOptions)
LoadOption changes what LoadConfig requires.
func OptionalPublicURL ¶ added in v0.2.0
func OptionalPublicURL() LoadOption
OptionalPublicURL lets {PREFIX}MAIL_PROVIDER=smtp start without {PREFIX}PUBLIC_URL, for a service whose mail carries no links (alerts, receipts). It is still validated when set. Without this option it is required, so a service that does send links cannot start without the origin they point at.
type Message ¶
type Message struct {
Kind string
To string
Subject string
Text string
HTML string // optional; with it the message is multipart/alternative
Attrs []slog.Attr
// Headers are extra header fields, such as List-Unsubscribe or a
// provider's tag header (X-SES-CONFIGURATION-SET, X-PM-Tag). The
// headers the package writes itself (From, To, Subject, Date,
// Message-ID, Reply-To, MIME-Version, Content-*) and Cc/Bcc are refused.
Headers map[string]string
// Attachments, when present, make the message multipart/mixed. Each is
// held in memory until sent, queued messages included.
Attachments []Attachment
}
Message is one email. Kind names it in logs ("password_reset"); Attrs are logged with its outcome and must never hold a secret (no token, no link, no body).
Example (Attachments) ¶
A receipt with a PDF and an unsubscribe header.
package main
import (
"github.com/kararnab/onemailer"
)
func main() {
var pdf []byte // the rendered receipt
_ = onemailer.Message{
Kind: "receipt",
To: "Ada <ada@example.org>",
Subject: "Your receipt",
Text: "Thanks for your order. Your receipt is attached.",
Headers: map[string]string{
"List-Unsubscribe": "<https://app.example.org/unsubscribe/abc>",
},
Attachments: []onemailer.Attachment{
{Filename: "receipt.pdf", Data: pdf}, // application/pdf, from the extension
},
}
}
Output:
type Outcome ¶ added in v0.2.0
type Outcome string
Outcome is what happened to one try of a message.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue delivers messages outside the request that produced them (so a slow server never stalls a request): a bounded in-process queue, one worker, and retries on a fixed schedule. A message that cannot be queued or delivered is dropped and logged; the user can ask again. A permanent failure (see IsPermanent) is not retried.
The queue lives in memory: what is queued or waiting for a retry is lost if the process dies, and dropped (and logged) when Close gives up. When a message must survive a restart, call a Sender from your own job system instead (README, "Delivery guarantees").
func NewQueue ¶
func NewQueue(sender Sender, cfg QueueConfig) *Queue
NewQueue starts a queue in front of sender.
func (*Queue) Close ¶
Close stops accepting messages and waits until every accepted one is sent or has failed for good, or until ctx ends; then what is left (queued, or waiting for a retry) is dropped and logged. A second Close waits for the first to finish, or for its own ctx.
type QueueConfig ¶
type QueueConfig struct {
Capacity int // default 256
Delays []time.Duration // before each try; default 0, 10 s, 1 min, 5 min
Logger *slog.Logger // default slog.Default()
// After replaces time.After in tests.
After func(time.Duration) <-chan time.Time
// OnResult, when set, is called with every outcome the queue logs, for
// metrics. It runs on the queue's goroutines and must return quickly.
OnResult func(Result)
}
QueueConfig tunes a Queue; the zero value gives the defaults.
Example (OnResult) ¶
Counting outcomes for metrics; the callback never sees a body or address.
package main
import (
"github.com/kararnab/onemailer"
)
func main() {
var sender onemailer.Sender // from NewSender
q := onemailer.NewQueue(sender, onemailer.QueueConfig{
OnResult: func(r onemailer.Result) {
// e.g. mailResults.WithLabelValues(r.Kind, string(r.Outcome), r.Reason).Inc()
_ = r
},
})
_ = q.Len() // queue depth, for a gauge
}
Output:
type Result ¶ added in v0.2.0
type Result struct {
Kind string
Attrs []slog.Attr
Outcome Outcome
Reason string // with OutcomeNotSent
Attempts int // tries made so far
Err error // the last failure, if any
Duration time.Duration // of the last try; 0 when none was made
}
Result reports one outcome to QueueConfig.OnResult. Like the logs, it carries the message kind and attributes, never the body or recipient.
type SMTPSender ¶
type SMTPSender struct {
// contains filtered or unexported fields
}
SMTPSender delivers over SMTP with the configured TLS mode. It verifies certificates against the host name and never skips verification.
func NewSMTPSender ¶
func NewSMTPSender(cfg Config) (*SMTPSender, error)
NewSMTPSender returns a sender for an smtp configuration. A Config built by hand rather than by LoadConfig gets the same defaults (port 587, starttls) and the same refusals: no sender, no host, an unknown TLS mode, or plain SMTP to a host that is neither loopback nor AllowPlainHost.
type Sender ¶
Sender delivers one message.
func NewSender ¶ added in v0.2.0
NewSender returns the sender for cfg: an SMTPSender when mail is on, and when it is off a sender that delivers nothing and answers ErrMailOff, so an application can always build its Queue the same way.
Example ¶
A service that sends mail off the request path. With MYAPP_MAIL_PROVIDER unset or none, NewSender gives a sender that delivers nothing, so the code is the same either way.
package main
import (
"context"
"log"
"log/slog"
"os"
"time"
"github.com/kararnab/onemailer"
)
func main() {
cfg, err := onemailer.LoadConfig(os.Getenv, "MYAPP_")
if err != nil {
log.Fatal(err)
}
sender, err := onemailer.NewSender(cfg)
if err != nil {
log.Fatal(err)
}
q := onemailer.NewQueue(sender, onemailer.QueueConfig{})
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
q.Close(ctx) // delivers what is queued, or gives up after 10 s
}()
ttl := time.Hour
q.Enqueue(onemailer.Message{
Kind: "password_reset", // logged as password_reset_sent / _not_sent
To: "reader@example.org",
Subject: "Reset your password",
Text: "Open this link within " + onemailer.Lifetime(ttl) + ": " + cfg.PublicURL + "/reset#token",
Attrs: []slog.Attr{slog.String("user_id", "u-42")}, // never a secret
})
}
Output:
Directories
¶
| Path | Synopsis |
|---|---|
|
Package mailtest is an in-process SMTP server for tests of onemailer and the code that uses it: plain, STARTTLS or implicit TLS, optional AUTH PLAIN, and scripted failures.
|
Package mailtest is an in-process SMTP server for tests of onemailer and the code that uses it: plain, STARTTLS or implicit TLS, optional AUTH PLAIN, and scripted failures. |