onemailer

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

OneMailer

Transactional email over plain SMTP for Go services: password resets, verification links, invites. No provider SDK and no provider-specific code, so the same build sends mail through a local catcher on a laptop and through Amazon SES, Postmark, SendGrid or Resend in production; only the configuration differs.

go get github.com/kararnab/onemailer

Standard library only. Extracted from CodeAtlas's mail package, where it delivers password-reset and invite emails, so that LibraryZ and CodeAtlas share one implementation.

What's in it

LoadConfig(getenv, prefix) Reads {PREFIX}MAIL_* / {PREFIX}SMTP_* settings and refuses inconsistent ones, naming the variable. Never prints the password.
SMTPSender Delivers one Message with the configured TLS mode. Certificates are always verified; plain SMTP only to loopback or one named catcher host; credentials never sent in clear.
Message Text, optional HTML (then multipart/alternative), UTF-8 quoted-printable, Message-ID, Reply-To. Header values with line breaks are refused.
Queue Delivers off the request path: bounded, one worker, retries after 10 s, 1 min and 5 min, then drops and logs. Logs carry the message kind and your attributes, never the body, link or recipient.
Lifetime Words a link lifetime for email copy ("1 hour", "30 minutes").
mailtest An in-process SMTP server for tests: plain, STARTTLS or implicit TLS, optional AUTH, scripted failures.

Templates and per-account sending caps belong to the application: they depend on its copy and its database.

Use

cfg, err := onemailer.LoadConfig(os.Getenv, "LIBRARYZ_")
if err != nil {
	log.Fatalf("mail: %v", err) // names the variable, e.g. LIBRARYZ_SMTP_HOST
}
log.Printf("mail: %s", cfg) // "smtp smtp.example.org:587 (starttls, login apikey), from …"

if cfg.Enabled() {
	sender, _ := onemailer.NewSMTPSender(cfg)
	q := onemailer.NewQueue(sender, onemailer.QueueConfig{})
	defer q.Close(context.Background())

	q.Enqueue(onemailer.Message{
		Kind:    "password_reset", // logged as password_reset_sent / _not_sent
		To:      "reader@example.org",
		Subject: "Reset your password",
		Text:    text,
		HTML:    html,
		Attrs:   []slog.Attr{slog.String("user_id", id)}, // never a secret
	})
}

Configuration

Every variable carries your prefix (LIBRARYZ_, CODEATLAS_, …).

Variable
MAIL_PROVIDER none (default: nothing is sent) or smtp
PUBLIC_URL The origin links point at. Required with smtp. https, or http for localhost or with ENV=development
MAIL_FROM A real, named sender: App <accounts@example.org>, not no-reply@ (people reply to reset emails, and filters score no-reply lower)
MAIL_REPLY_TO Optional; an inbox someone reads
SMTP_HOST Required with smtp
SMTP_PORT Default 587
SMTP_TLS starttls (default), tls (implicit, usually 465) or none
SMTP_ALLOW_PLAIN_HOST The one non-loopback host allowed with SMTP_TLS=none, for a catcher on a container network (mailpit)
SMTP_USERNAME When the server requires a login
SMTP_PASSWORD_FILE Preferred; or SMTP_PASSWORD. At most one

Development: Mailpit

Mailpit keeps every message and shows it in a browser; nothing leaves the machine. In Docker Compose:

mailpit:
  image: axllent/mailpit:v1.31.4@sha256:b68349e3a014b90c5610bfb26b2ae36f3892d7b8cf25ee140c6c71c98d2fcf48
  ports: ["8025:8025"]   # inbox at http://localhost:8025

and point the service at it:

{P}MAIL_PROVIDER=smtp  {P}SMTP_HOST=mailpit  {P}SMTP_PORT=1025
{P}SMTP_TLS=none       {P}SMTP_ALLOW_PLAIN_HOST=mailpit
{P}MAIL_FROM='App <accounts@app.localhost>'  {P}PUBLIC_URL=http://localhost:8081

End-to-end tests can read links back from GET http://localhost:8025/api/v1/messages.

Going to production

Code changes: none.

  1. Pick a provider and verify the sending domain. Any SMTP provider works:

    Provider Host (check the provider's docs) Port / TLS Username
    Amazon SES email-smtp.<region>.amazonaws.com 587 starttls the SMTP credential's user
    Postmark smtp.postmarkapp.com 587 starttls server API token
    SendGrid smtp.sendgrid.net 587 starttls apikey
    Resend smtp.resend.com 465 tls resend

    Add the DNS records the provider gives you: SPF, DKIM, and DMARC (start with p=none and a report address). Without SPF and DKIM, mail goes to spam or is refused. SES starts new accounts in a sandbox that only mails verified addresses.

  2. Set the environment above, with SMTP_PASSWORD_FILE pointing at a secret file. The service should refuse to start on a bad setting.

  3. Send a test message from the production host with your service's send-test command (build Message by hand and call SMTPSender.Send synchronously; print SMTPCode(err) on failure). Check the received headers for spf=pass, dkim=pass, dmarc=pass.

  4. Exercise one real flow (a password reset) and confirm the logs show the kind and no link or token.

License

MIT

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.

Index

Constants

View Source
const (
	ProviderNone = "none"
	ProviderSMTP = "smtp"
)

Providers ({PREFIX}MAIL_PROVIDER).

View Source
const (
	TLSStartTLS = "starttls"
	TLSImplicit = "tls"
	TLSNone     = "none"
)

TLS modes ({PREFIX}SMTP_TLS).

Variables

View Source
var DefaultDelays = []time.Duration{0, 10 * time.Second, time.Minute, 5 * time.Minute}

DefaultDelays is the retry schedule: at once, then after 10 s, 1 min and 5 min.

View Source
var ErrHeaderInjection = errors.New("onemailer: a header value contains a line break")

ErrHeaderInjection is returned for a header value holding CR or LF.

Functions

func IsLoopback

func IsLoopback(host string) bool

IsLoopback reports whether host is localhost or a loopback IP address.

func Lifetime

func Lifetime(d time.Duration) string

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.

func SMTPCode

func SMTPCode(err error) int

SMTPCode returns the SMTP reply code inside err, or 0.

Types

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

func LoadConfig(getenv func(string) string, prefix string) (Config, error)

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;
                          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.

func (Config) Addr

func (c Config) Addr() string

Addr is host:port.

func (Config) Enabled

func (c Config) Enabled() bool

Enabled reports whether mail is sent.

func (Config) GoString

func (c Config) GoString() string

GoString keeps %#v from printing the password too.

func (Config) String

func (c Config) String() string

String describes the configuration for logs, without the password.

func (Config) WithRootCAs

func (c Config) WithRootCAs(pool *x509.CertPool) Config

WithRootCAs returns c trusting only pool for the server certificate. For tests against mailtest's TLS modes; production uses the system roots.

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
}

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).

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.

func NewQueue

func NewQueue(sender Sender, cfg QueueConfig) *Queue

NewQueue starts a queue in front of sender.

func (*Queue) Close

func (q *Queue) Close(ctx context.Context)

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.

func (*Queue) Enqueue

func (q *Queue) Enqueue(m Message) bool

Enqueue accepts m for delivery and reports whether it was accepted. It never blocks: a full or closed queue drops m and logs why.

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
}

QueueConfig tunes a Queue; the zero value gives the defaults.

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.

func (*SMTPSender) Send

func (s *SMTPSender) Send(ctx context.Context, m Message) error

Send connects, upgrades or starts TLS as configured, authenticates when a username is set, and delivers m.

type Sender

type Sender interface {
	Send(ctx context.Context, m Message) error
}

Sender delivers one message.

Directories

Path Synopsis
Package mailtest is an in-process SMTP server for tests of internal/mail and its users: plain, STARTTLS or implicit TLS, optional AUTH PLAIN, and scripted failures.
Package mailtest is an in-process SMTP server for tests of internal/mail and its users: plain, STARTTLS or implicit TLS, optional AUTH PLAIN, and scripted failures.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL