mailer

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT-0 Imports: 13 Imported by: 3 modules, 1 package

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

mailer

Transactional mail for Go applications, behind one Sender interface.

sender, err := mailer.NewSMTPSender(mailer.SMTPConfig{
    Host: "smtp.example.com", Port: 587,
    Username: "shop@example.com", Password: os.Getenv("SMTP_PASSWORD"),
    From: "shop@example.com",
    TLS:  mailer.TLSStartTLS,
})

err = sender.Send(ctx, mailer.Message{
    To:      []string{"jane@example.com"},
    Subject: "Order 1042 — payment received",
    Text:    plain,
    HTML:    html, // optional; becomes the multipart/alternative part
})

Delivery is SMTP, via go-mail. Discard and Fake implement Sender too — the first for a deployment with no mail configured, the second for tests.

Microsoft Exchange Online

Basic Auth for SMTP client submission is going away, so an Exchange mailbox is reached with XOAUTH2: the password becomes an OAuth2 access token. go-mail speaks XOAUTH2 but has no notion of where a token comes from, which is what mailer/msauth is for.

tokens, err := msauth.New(tenantID, clientID, clientSecret)

sender, err := mailer.NewSMTPSender(mailer.SMTPConfig{
    Host: "smtp.office365.com", Port: 587,
    Username:    "shop@example.com", // the mailbox; XOAUTH2 authenticates as a named one
    TokenSource: tokens,             // Password is then ignored
    From:        "shop@example.com",
    TLS:         mailer.TLSStartTLS,
})

A token is fetched for each send and cached until a minute before it expires, so nothing here has to reason about expiry.

Graph, as an alternative to SMTP

GraphSender sends through the Microsoft Graph API's sendMail endpoint instead of SMTP, for a deployment that already has an Entra app registration and would rather not deal with SMTP AUTH. It needs its own token, scoped to Graph rather than SMTP:

tokens, err := msauth.New(tenantID, clientID, clientSecret, msauth.WithScope(msauth.ScopeGraph))

sender, err := mailer.NewGraphSender(mailer.GraphConfig{
    TokenSource: tokens,
    From:        "shop@example.com", // needs the Mail.Send application permission, admin-consented
})

The app registration needs a different permission than the SMTP path: Mail.Send (application, admin-consented), not SMTP.SendAsApp. The two are not interchangeable, and a token that works for one will be rejected by the other.

Sends go as raw MIME rather than through Graph's JSON message schema, which is what lets a message carry both a plain-text and an HTML part — the JSON schema's body takes exactly one contentType. The cost is that Bcc has no envelope on this transport: it is written into the MIME as a real header, which Microsoft's documented behaviour says Graph reads as recipients and strips before delivering. That behaviour has not been verified against a live tenant by this module's maintainer — confirm it with a real send before relying on Bcc through Graph in production.

Which transport to reach for: SMTPSender is the default. GraphSender is for a deployment where the tenant-side XOAUTH2 setup (SMTP AUTH enabled per mailbox, a service principal, SMTP.SendAsApp) is a bigger lift than a Mail.Send grant, or where Graph is already how the deployment talks to that tenant for something else.

The tenant-side setup is the part that bites, and none of it is visible from this library — a tenant that has not been set up returns a token perfectly happily and the mail server then refuses it. You need, at minimum:

  • an Entra ID app registration with the SMTP.SendAsApp application permission (Office 365 Exchange Online), with admin consent;
  • a service principal for that app registered in Exchange Online;
  • Send As granted on the mailbox;
  • SMTP AUTH enabled for that mailbox — it is disabled tenant-wide by default.

Check each against current Microsoft documentation; these requirements move.

Behaviour worth knowing

  • A password is never sent in the clear. Authentication mechanism selection refuses PLAIN and LOGIN on an unencrypted connection. A local mail sink reached over TLSNone must therefore be configured with no credentials, not throwaway ones — which is also the right shape, since such a sink does not check them.
  • STARTTLS is mandatory, not opportunistic. A relay that offers no STARTTLS fails loudly rather than quietly sending in the clear. TLSNone is the explicit opt-out.
  • Bcc reaches the envelope and never the headers, which is what keeps blind recipients blind.
  • Nothing retries, queues or logs. A Sender performs one delivery attempt and returns. What a failure means is the caller's decision.
  • Message.ReplyTo overrides SMTPConfig.ReplyTo, for mail sent on somebody's behalf that should be answered to them.

Message rules

Text is required; HTML is optional and becomes the alternative part, so a client that refuses HTML still shows something readable. Subject must be present and must not contain a line break — header values are written verbatim, so a newline would inject arbitrary headers, and it is rejected rather than silently rewritten.

Message carries only fields that mean the same thing to every transport. Adding one is a decision, not a convenience.

License

This module is licensed under the MIT No Attribution license.

Documentation

Overview

Package mailer sends transactional mail, and hides which mechanism does it behind a single Sender interface.

The interface is the point of the package. An application's tests capture mail through Fake rather than talking to a mail server, and a deployment with no mail configured can use Discard, so an unconfigured relay is never the reason a request fails.

Scope

Message carries only fields that mean the same thing to every transport. Adding one is a decision, not a convenience: if a field only makes sense to a single application, it belongs in that application's code, not here. That rule is the only thing keeping this struct from accumulating everything anyone ever needed.

Transports

SMTPSender is the default and the one most deployments want: a password, or — for a Microsoft Exchange Online mailbox now that Basic Auth for SMTP client submission is going away — a TokenSource for XOAUTH2. GraphSender exists alongside it for a deployment that already has an Entra app registration and would rather call the Microsoft Graph API than deal with SMTP AUTH at all; it needs its own TokenSource, scoped to Graph rather than to SMTP. The msauth subpackage implements a TokenSource against Microsoft's client-credentials flow for either audience — see msauth.ScopeSMTP and msauth.ScopeGraph.

Both Microsoft transports carry the same caveat: the tenant-side setup — admin consent, a service principal, mailbox-level permissions — is invisible from here, and a misconfigured tenant hands out a token happily and fails only at the send.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Discard

type Discard struct{ Log *slog.Logger }

Discard is the Sender for a deployment with no mail configured. It logs what it would have sent, at warning level, and reports success.

Reporting success is deliberate. The alternative — an error — would make every request log a delivery failure for a deployment that simply has not configured mail, burying the failures that matter. A loud warning at startup is where that problem is meant to be noticed.

func (Discard) Send

func (d Discard) Send(_ context.Context, m Message) error

type Fake

type Fake struct {
	// Err, when set, is returned by every Send, standing in for a mail server
	// that is refusing or unreachable.
	Err error
	// contains filtered or unexported fields
}

Fake captures messages instead of sending them. It backs every test that involves mail, and lives here next to the interface rather than in a separate test-only package so that a caller needs one import rather than two.

func NewFake

func NewFake() *Fake

func (*Fake) Attempted

func (f *Fake) Attempted() []Message

Attempted returns every message handed to Send, including ones Err refused. It answers the different question of whether the caller tried at all, which is what distinguishes "the handler never sent" from "the send was refused".

func (*Fake) Send

func (f *Fake) Send(_ context.Context, m Message) error

Send records the message unless Err is set. It does not validate: a test asserting on what a handler tried to send should see what the handler built, not a rejection this type invented.

func (*Fake) Sent

func (f *Fake) Sent() []Message

Sent returns every message that was delivered, in order. A send that failed because Err was set is not among them — Sent answers "what went out".

func (*Fake) To

func (f *Fake) To(address string) []Message

To returns the delivered messages addressed to one recipient, which is what a test usually wants to assert on. A message matches if the address is among its To recipients; Bcc is not searched, because a test asking "did this person get it" and a test asking "was this person blind-copied" are different questions.

type GraphConfig

type GraphConfig struct {
	// TokenSource supplies the bearer token. Build one with msauth.New and
	// msauth.WithScope(msauth.ScopeGraph) — the Graph API needs a different
	// token audience than SMTP, so an SMTP TokenSource must not be reused here.
	TokenSource TokenSource

	// From is the mailbox to send as. The app registration's client credentials
	// grant needs the SMTP.SendAsApp permission is NOT what Graph uses — Graph
	// needs the Mail.Send *application* permission, admin-consented, scoped (via
	// an access policy) to this mailbox.
	From string
	// ReplyTo is the default for messages that do not set their own.
	ReplyTo string

	// HTTPClient is used for the sendMail call. nil uses a package default with
	// a 30 second timeout, applied only when the caller's context has no
	// deadline.
	HTTPClient *http.Client
	Timeout    time.Duration
	// contains filtered or unexported fields
}

GraphConfig is what GraphSender needs.

type GraphSender

type GraphSender struct {
	// contains filtered or unexported fields
}

GraphSender delivers mail through the Microsoft Graph API's sendMail endpoint, as the mailbox named by From.

It exists alongside SMTPSender rather than instead of it because Graph is not a drop-in replacement for a relay: it is a per-mailbox API with its own throttling and its own permission model, appropriate for a deployment that already has an Entra app registration and would rather not deal with SMTP AUTH at all. Most deployments want SMTPSender with a TokenSource, or a password, or a dedicated transactional relay — see the package doc.

func NewGraphSender

func NewGraphSender(cfg GraphConfig) (*GraphSender, error)

NewGraphSender validates the configuration and returns a Sender.

It deliberately does not fetch a token: an identity provider that is unreachable at boot is not a reason to refuse to start an application whose job does not depend on mail. The first send is where a credential or permission problem surfaces.

func (*GraphSender) Send

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

Send delivers one message, as a raw RFC 5322 message posted to sendMail rather than through Graph's JSON message schema.

Raw MIME is what lets a message carry both a plain-text and an HTML part — the JSON schema's body takes exactly one contentType, so a receipt that must stay readable in a client that refuses HTML would not be expressible through it. The cost is that Bcc, which the JSON schema has a field for, has to be written into the MIME as a real header instead (see mimeOptions.BccInHeaders): Microsoft's documented behaviour is that Graph reads recipients from the message headers on this path and strips Bcc before delivering, so it still ends up hidden from the other recipients — but that behaviour has not been verified against a live tenant by this package's author, and is worth confirming with a real send before relying on it for a deployment that uses Bcc.

type Inline

type Inline struct {
	// ContentID is what the HTML names it by, without angle brackets — "qr-1",
	// referenced as <img src="cid:qr-1">. Unique within a message.
	ContentID string
	// ContentType is the image's MIME type, such as image/png.
	ContentType string
	Data        []byte
}

Inline is one image an HTML body refers to as cid:ContentID.

type Message

type Message struct {
	// To is the visible recipients. At least one must be a non-blank address.
	To []string
	// Bcc is the blind recipients, delivered through the SMTP envelope and never
	// written into the message headers — which is what keeps them blind.
	Bcc []string

	Subject string
	Text    string
	HTML    string

	// ReplyTo overrides the sender's configured default for this one message. It
	// exists for mail sent on somebody's behalf — an enquiry that a recipient
	// should be able to answer by replying to the person who sent it, rather than
	// to the mailbox the software sends from.
	ReplyTo string

	// Inline is images the HTML body shows by reference — <img src="cid:ID"> —
	// carried inside the message rather than fetched from a server. A ticket's
	// QR code is the case it exists for: an image a mail client will not block
	// as remote content, and that still shows with the reader offline at a door.
	//
	// It means the same thing to every transport, which is the bar for a field
	// here (see the package doc): both write the message as MIME, where an
	// inline part is a multipart/related sibling of the HTML.
	Inline []Inline
}

Message is one email. Text is required and HTML is optional: a receipt has to arrive readable even in a client that refuses HTML, and a plain-text part is also what keeps a transactional message out of spam folders.

func (Message) Validate

func (m Message) Validate() error

Validate checks a Message is sendable, so a template that produced nothing is caught here rather than as a puzzling rejection from a mail server.

type SMTPConfig

type SMTPConfig struct {
	Host string
	Port int

	// Username and Password may both be empty, for a relay on a private network
	// that authenticates by address — a local mail sink in development being the
	// obvious case. No credentials means no authentication is attempted at all,
	// rather than an empty PLAIN attempt that such a relay would refuse.
	Username string
	Password string

	// TokenSource, when set, selects XOAUTH2 instead of a password: Username is
	// the mailbox and the token is fetched fresh for each send. Password is then
	// ignored. This is the path to a Microsoft Exchange Online mailbox.
	TokenSource TokenSource

	// From is the envelope and header sender. A mail server will usually reject
	// a From it does not consider itself responsible for, so this has to be an
	// address on a domain the relay accepts.
	From string
	// ReplyTo is the default for messages that do not set their own, and is where
	// a reply should land when that is not the From address.
	ReplyTo string

	TLS     TLSPolicy
	Timeout time.Duration
}

SMTPConfig is what SMTPSender needs.

type SMTPSender

type SMTPSender struct {
	// contains filtered or unexported fields
}

SMTPSender delivers mail over SMTP.

func NewSMTPSender

func NewSMTPSender(cfg SMTPConfig) (*SMTPSender, error)

NewSMTPSender validates the configuration and returns a Sender.

It deliberately does not connect, and does not fetch a token: a mail server that is down at boot is not a reason to refuse to start an application whose job does not depend on mail. The first send is where a connection or credential problem surfaces.

func (*SMTPSender) Send

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

Send delivers one message.

The order matters: the message is validated before a token is fetched, so a template that rendered nothing does not cost a round trip to an identity provider, and a credential problem is never reported for a message that was never sendable.

type Sender

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

Sender delivers a Message. Implementations must be safe for concurrent use: two requests can want to send at once.

A Sender performs one delivery attempt and returns. It does not retry, does not queue and does not log. What a failed send means — a dropped receipt, an error shown to a visitor, a page that renders anyway — is the caller's decision, and different applications decide differently.

type TLSPolicy

type TLSPolicy string

TLSPolicy is how the connection to the mail server is secured.

const (
	// TLSStartTLS upgrades a plain connection and requires the upgrade to
	// succeed. This is the default and the right answer for port 587.
	TLSStartTLS TLSPolicy = "starttls"
	// TLSImplicit dials TLS directly, which is what port 465 expects.
	TLSImplicit TLSPolicy = "tls"
	// TLSNone sends credentials and message contents in the clear. It exists for
	// a local mail sink such as mailpit in development; it is never right against
	// a mail server that is not on the same machine.
	TLSNone TLSPolicy = "none"
)

func ParseTLSPolicy

func ParseTLSPolicy(s string) (TLSPolicy, error)

ParseTLSPolicy converts a configured string, naming the valid values on failure rather than falling back to a default — silently downgrading somebody's TLS because they wrote "ssl" would be the worst of the options.

type TokenSource

type TokenSource interface {
	Token(ctx context.Context) (string, error)
}

TokenSource supplies an OAuth2 access token for XOAUTH2 authentication.

It is declared here, where it is consumed, rather than in the package that implements it, so that a caller can substitute their own without this package importing anyone.

Directories

Path Synopsis
Package msauth acquires Microsoft access tokens for XOAUTH2 authentication, using the OAuth2 client-credentials flow (app-only auth).
Package msauth acquires Microsoft access tokens for XOAUTH2 authentication, using the OAuth2 client-credentials flow (app-only auth).

Jump to

Keyboard shortcuts

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