Documentation
¶
Overview ¶
Package mail is the mail battery: transactional mail — a sign-in code, a password reset, an order confirmation — sent with one value and the standard library only.
type Config struct {
chok.Base
Mail mail.Config `yaml:"mail"`
}
//go:embed templates
var templates embed.FS
m := mail.MustNew(cfg.Mail, mail.Templates(templates))
err := m.Send(ctx, mail.Message{To: []string{order.Email}, Template: "order-confirmed", Data: order})
Transports ¶
Config.Transport smtp sends through a relay (Resend, Postmark, Amazon SES and the like all offer one, and sign DKIM for you): each Send dials it, upgrades with STARTTLS or speaks TLS from the start, authenticates with AUTH PLAIN and delivers to every recipient, Bcc included, within Config.Timeout. dir writes every mail as an .eml file instead, for development and tests; log only logs it. The Sender option replaces the transport with a function, for an HTTP API or a test.
Templates ¶
With Templates, Message.Template names a template: {name}.html (html/template, sent as text/html), {name}.txt (text/template, sent as text/plain) or both, which go out together as multipart/alternative. _*.html and _*.txt files are partials, and {{define "subject"}} sets the subject.
Composition ¶
A mail is RFC 5322: From, Reply-To, To, Cc, Subject (encoded when not ASCII), Date, a Message-ID at From's domain and MIME-Version; the text in quoted-printable, attachments in base64; text and HTML in multipart/alternative, inside multipart/related with inline images, inside multipart/mixed with attachments. Bcc never appears.
Reliability ¶
Send is one attempt. To retry, enqueue the mail with jobs in the transaction that calls for it, and send it from the topic's Worker: docs/mail.md has the recipe, and the identity adapter.
Example ¶
A mailer with templates; here a Sender stands in for the relay and prints what would go out.
package main
import (
"context"
"fmt"
"testing/fstest"
"github.com/zynthara/chok/mail"
)
func main() {
templates := fstest.MapFS{ // usually an embed.FS of a templates directory
"order-confirmed.html": {Data: []byte(`{{define "subject"}}Order {{.ID}} confirmed{{end}}<p>Thanks, {{.Name}}!</p>`)},
"order-confirmed.txt": {Data: []byte(`Thanks, {{.Name}}!`)},
}
m, err := mail.New(mail.Config{From: "Shop <no-reply@shop.example>"},
mail.Templates(templates),
mail.Sender(func(_ context.Context, msg *mail.Message, raw []byte) error {
fmt.Printf("%s, to %v\n%s\n%s\n", msg.Subject, msg.To, msg.Text, msg.HTML)
return nil
}))
if err != nil {
fmt.Println(err)
return
}
order := struct {
ID int
Name string
}{42, "Ada"}
if err := m.Send(context.Background(), mail.Message{To: []string{"Ada <ada@example.com>"}, Template: "order-confirmed", Data: order}); err != nil {
fmt.Println(err)
}
}
Output: Order 42 confirmed, to [Ada <ada@example.com>] Thanks, Ada! <p>Thanks, Ada!</p>
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Attachment ¶
type Attachment struct {
// Name is the file name the recipient sees and, for an Inline
// attachment, its Content-ID: the HTML shows it as <img src="cid:Name">.
Name string
// ContentType is the media type; empty, it is guessed from Name's
// extension, and is application/octet-stream when that fails.
ContentType string
// Content is the file.
Content []byte
// Inline makes it part of the HTML body (multipart/related) rather than
// an attachment of its own.
Inline bool
}
Attachment is a file that travels with a mail.
Example ¶
An attachment, and an image the HTML shows inline.
package main
import (
"github.com/zynthara/chok/mail"
)
func main() {
logo, invoice := []byte("…png…"), []byte("…pdf…")
msg := mail.Message{
To: []string{"ada@example.com"},
Subject: "Your invoice",
HTML: `<img src="cid:logo.png" alt="Shop"><p>Your invoice is attached.</p>`,
Attachments: []mail.Attachment{
{Name: "logo.png", Content: logo, Inline: true},
{Name: "invoice-42.pdf", Content: invoice}, // application/pdf, from the extension
},
}
_ = msg // m.Send(ctx, msg)
}
Output:
type Config ¶
type Config struct {
// Transport is how a mail leaves: smtp sends it; dir writes it as an
// .eml file into Dir, for development, examples and tests; log only
// logs it. A Sender option replaces the transport, and then
// Transport and its settings are ignored.
Transport string `yaml:"transport" default:"smtp" validate:"omitempty,oneof=smtp dir log"`
// From is the sender, "Name <addr>" or "addr"; required. Message-IDs
// take its domain.
From string `yaml:"from"`
// ReplyTo is where replies go, when not to From.
ReplyTo string `yaml:"reply_to"`
// Dir is where transport dir writes, one {unix nanoseconds}-{random}.eml
// file per mail; required with it, and created by New.
Dir string `yaml:"dir"`
// Timeout bounds one Send: dialing, TLS, authentication and delivery.
Timeout time.Duration `yaml:"timeout" default:"15s"`
// SMTP is the relay transport smtp sends through.
SMTP SMTPConfig `yaml:"smtp"`
}
Config is the mail section of an application's configuration:
mail:
from: Shop <no-reply@shop.example>
smtp:
host: smtp.example.com
username: apikey
The SMTP password is a secret: set it from the environment (SHOP_MAIL_SMTP_PASSWORD for an app loaded as "shop"), never in a file. New gives an empty Transport or TLS and a zero Timeout or Port the defaults below, whether the Config comes from a file or from code.
type Mailer ¶
type Mailer struct {
// contains filtered or unexported fields
}
Mailer sends mail: m.Send(ctx, mail.Message{To: …, Template: …, Data: …}). Each Send composes the message and hands it to the transport on its own connection; there is no pool and no queue — for retries, send from a jobs Worker. Register it with app.Use, or not: it only reports a name and a health that is always nil.
func New ¶
New builds a mailer: it checks cfg, what the transport needs and every template, and creates transport dir's directory; it does not touch the network. A Config from chok.Load carries the defaults; one built in code gets them for its zero fields.
func (*Mailer) Health ¶
Health is always nil: every Send dials anew, so there is nothing to watch between them.
func (*Mailer) Send ¶
Send composes msg and delivers it through the transport within Config.Timeout. A bad recipient address, a Template that does not exist, a Template given with Text or HTML, a header Headers may not set: these are plain errors, not chok.Coder ones — a handler wraps them in its own. A transport failure wraps the transport's error. Errors leave the subject and the recipients out — a subject may carry a sign-in code, and errors end up in logs.
func (*Mailer) SendTemplate ¶
SendTemplate sends one address the template named template, rendered with data: Send(ctx, Message{To: []string{to}, Template: template, Data: data}). It has the shape of identity's Sender, so a mailer wires into identity in one line: identity.Sender(mailer.SendTemplate).
type Message ¶
type Message struct {
// To, Cc and Bcc are the recipients, each "Name <addr>" or "addr".
// Bcc recipients get the mail without appearing in it.
To, Cc, Bcc []string
// Subject is the subject line; with a Template, a non-empty Subject
// replaces the template's.
Subject string
// Text and HTML are the body: plain text, HTML, or both, which go out
// as multipart/alternative.
Text, HTML string
// Template names a template of the Templates option, without its
// extension; Data is what it renders.
Template string
Data any
// Headers are extra header fields, such as List-Unsubscribe; one named
// Reply-To replaces Config.ReplyTo. From, To, Cc, Bcc, Subject, Date,
// Message-ID, MIME-Version and the Content-* fields are the mailer's:
// setting one is an error.
Headers map[string]string
// Attachments travel with the mail.
Attachments []Attachment
}
Message is one mail. Give its body either as a Template, rendered with Data, or directly as Text, HTML or both; and at least one recipient.
type Option ¶
type Option func(*options)
Option configures New.
func Logger ¶
Logger is where the mailer logs; the default is slog.Default(). On a request the lines carry its request_id.
func Sender ¶
Sender replaces the transport, Config.Transport and its settings included: fn gets each composed message — m as rendered, its Subject, Text and HTML filled from the template — and raw, its RFC 5322 text, ready for an HTTP API or a test to take.
func Templates ¶
Templates gives the mails their templates: in fsys, a template {name} is {name}.html, an html/template sent as text/html, {name}.txt, a text/template sent as text/plain, or both, sent as multipart/alternative. Message names one by {name}, without the extension, wherever it sits in fsys (an embed.FS of a templates directory works as it is). Files named _*.html, or _*.txt, are partials every template of their kind can call; {{define "subject"}}…{{end}} in a template is the subject — the .txt one's when both define it — unless Message.Subject is set. A template that does not parse fails New, and so does giving Templates twice.
type SMTPConfig ¶
type SMTPConfig struct {
// Host is the relay; required with transport smtp.
Host string `yaml:"host"`
// Port is the relay's port: 587 with starttls, 465 with implicit.
Port int `yaml:"port" default:"587"`
// Username and Password authenticate with AUTH PLAIN, over TLS only
// (or to a loopback host); an empty Username skips authentication.
Username string `yaml:"username"`
Password string `yaml:"password" secret:"true"`
// TLS is starttls (upgrade the plain connection; the relay must offer
// it), implicit (TLS from the first byte) or none, which only a
// loopback host may use, for local debugging.
TLS string `yaml:"tls" default:"starttls" validate:"omitempty,oneof=starttls implicit none"`
}
SMTPConfig is mail.smtp: the relay a transport smtp mail goes through, such as Resend's, Postmark's or Amazon SES's. Each Send dials it anew.