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 ¶
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.
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 (*Fake) Attempted ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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). |