mail

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 18 Imported by: 0

README

Mail portability

arkoren.dev/core/service/mail defines portable message fields. Drivers can impose provider constraints that callers must account for.

Capability Portable contract Mailgun limitation
Inline attachments ContentID identifies HTML cid: content; ContentType describes attachment data. ContentID must equal Filename, and the Mailgun SDK selects the uploaded content type instead of preserving ContentType.

Install with go get arkoren.dev/core. Start with sending a message, then choose a mail driver. A successful send is acceptance, not delivery. The facade does not retry, queue, or register provider notification endpoints automatically.

MIME wire constraints

SMTP and SES use mail.EncodeMIME; provider API mappings are separate. The encoder preserves attachment media-type parameters and declares the actual root type for every multipart/related container. With both text and HTML bodies, that root is multipart/alternative, including inside multipart/mixed.

Every emitted physical line is limited to 998 bytes excluding CRLF. The encoder keeps its encoded-word and recipient-list folding. If a subject, individual mailbox, filename, or other header still exceeds the limit, encoding returns ErrInvalidMessage and no bytes rather than truncating or rewriting your data. Construction can therefore succeed while MIME encoding fails. This is a wire limit, not a new universal provider limit on Message declarations. Native MIME readers accepting a message do not prove its physical-line conformance.

Supply an uncommented, unfolded modern RFC 5322 Message-ID: <left@right>, where left is dot-atom-text and right is dot-atom-text or a bracketed no-fold-literal. The encoder rejects empty IDs, empty dot components, whitespace, comments, obsolete quoted forms, controls, and non-ASCII IDs with ErrInvalidMessage and no bytes. Valid supplied IDs remain byte-for-byte unchanged.

mail.NewMessageID generates a random left side and validates the supplied right-side syntax before generation. Raw IPv6 addresses become [IPv6:address]; other accepted domain bytes, including case and existing brackets, are preserved. Syntax validation does not check DNS, domain ownership, or provider policy.

Observing failures without exposing recipients

Configure mail.Builder.Events to observe returned outcomes. mail.FailedEvent contains ErrorClass, Recipients, and Attachments, not the diagnostic error. The classification is context.Canceled, context.DeadlineExceeded, mail.ErrInvalidMessage, or error for another failure, in that priority order. It does not establish whether a provider accepted or delivered the message.

For an existing bus *event.Bus, with imports context and arkoren.dev/core/service/mail, a listener can select an action without receiving SMTP diagnostics that might name a hidden recipient. alerts.Notify(context.Context, string) error is your application-owned notification service:

stop, err := bus.Listen(mail.Failed, func(ctx context.Context, observed mail.FailedEvent) error {
	if observed.ErrorClass == "mail.ErrInvalidMessage" {
		return nil // Correct construction at the sending call site.
	}
	return alerts.Notify(ctx, observed.ErrorClass) // Application-owned safe alert.
})
defer stop()

Migrate listeners that previously read FailedEvent.Err to ErrorClass; that field is intentionally removed rather than retaining sensitive causes. The error returned by Mailer.Send still preserves its original causes for errors.Is and errors.As. Treat those diagnostics as sensitive at the call site. Driver panics still propagate without either outcome event, and Sent still means acceptance, not delivery.

Documentation

Overview

Package mail provides portable transactional email submission and MIME encoding.

Messages

NewMessage takes required Recipients and Body records, followed by optional MessageBuilder callbacks for From, Subject, ReplyTo and Attachments. At least one recipient across To, CC and BCC and one text or HTML representation are required. Callbacks run directly once, synchronously in order, even for invalid inputs; nil entries panic. Err preserves the first domain error. Omitted From is valid during construction because Mailer.Send can supply its default; Validate, CheckSend and EncodeMIME require the completed sender. The zero Message is invalid.

message := mail.NewMessage(mail.Recipients{
	To: []mail.Address{{Email: "person@example.com"}},
}, mail.Body{Text: "Hello."}, func(letter *mail.MessageBuilder) {
	letter.Subject("Welcome")
})
if err := message.Err(); err != nil {
	return err
}
if _, err := mailer.Send(ctx, message); err != nil {
	return err
}

Message owns its address lists, attachment records and attachment bytes. Construction detaches inputs and the completed draft; slice getters detach their results. Retained drafts and getter output cannot change a publication. Send completes defaults in a copy without replaying callbacks or mutating the caller's message. Drivers keep BCC destinations out of visible headers.

MIME encoding

EncodeMIME serializes a message with a completed sender without applying mailer defaults. Attachment ContentType accepts media-type parameters, such as "text/plain; charset=UTF-8"; encoding preserves them except that Filename overrides any supplied "name" parameter and sets the disposition's filename. An empty ContentType is invalid, not an implicit application/octet-stream. Metadata that cannot be formatted as MIME returns an error wrapping ErrInvalidMessage and no encoded bytes. SMTP and SES drivers use this encoder; other provider mappings can have different attachment limits. Related multipart containers declare the actual root type: text/plain, text/html, or multipart/alternative for dual bodies, including nested containers. Every encoded physical line is limited to 998 bytes excluding CRLF. Existing encoded-word and recipient-list folding is retained; lines that still exceed the limit return ErrInvalidMessage and no partial bytes. Caller text, names, and attachment metadata are not truncated or rewritten to force acceptance. Supplied Message-IDs must use the uncommented, unfolded modern RFC 5322 form described by EncodeMIME and are preserved verbatim. NewMessageID validates its domain syntax and formats raw IPv6 addresses as [IPv6:address]. Neither API establishes domain ownership or provider acceptance. See EncodeMIME for an example.

Telemetry

With Builder.Telemetry, or telemetry.Default when it is not set, each Mailer.Send with a nonnil context emits a client span "mail send" with recipient and attachment counts, and the arkoren.mail.operations and arkoren.mail.operation.duration metrics, for every driver. These count attempts, not confirmed acceptances. A driver panic still ends the mailer's own span and records the attempt, without ending the caller's span or recording the panic value. A panic alone sets neither error.type nor an error status. Addresses, subject, body, attachments, headers and receipts are never recorded. Disabled telemetry costs nothing.

mailer := mail.New(driver, func(mailer *mail.Builder) {
	mailer.Telemetry(app.Telemetry())
})

Events

With Builder.Events, Mailer.Send publishes Sent ("mail.sent") with the receipt after driver acceptance, or Failed ("mail.failed") with a bounded class for a returned validation or driver error. A nil context fails before telemetry or events. Send's returned error preserves the original causes. A driver panic propagates unchanged and publishes neither event; it is not converted into a returned error. Failure payloads contain only counts and FailedEvent.ErrorClass, never diagnostic text, addresses, or message content. Classification does not establish whether a provider accepted a submission.

mailer := mail.New(driver, func(mailer *mail.Builder) {
	mailer.Events(app.Events())
})

New takes Builder policies for From, ReplyTo, Telemetry and Events. Policies run directly once in order on a fresh draft; nil entries panic and expanded nil/empty slices supply no edits. ReplyTo replaces and copies the input list; publication copies it again. Mailer.Config reports copied defaults, not a construction input. Drivers and reporting services remain shared dependencies.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Sent reports a returned driver acceptance when Builder.Events is set.
	// It is synchronous and best effort, never confirmation of delivery.
	// Driver panics publish no outcome; listener failures cannot replace it.
	//
	// Example:
	//
	//	stop, err := bus.Listen(mail.Sent, func(ctx context.Context, observed mail.SentEvent) error {
	//		fmt.Println(observed.Recipients)
	//		return nil
	//	})
	//	if err != nil {
	//		return err
	//	}
	//	defer stop()
	Sent = event.NewTopic[SentEvent]("mail.sent")

	// Failed reports a returned validation or driver error, excluding a nil
	// context rejected before instrumentation. Its bounded payload cannot leak
	// the diagnostic error returned by Send. It does not prove non-delivery.
	//
	// Example:
	//
	//	stop, err := bus.Listen(mail.Failed, func(ctx context.Context, observed mail.FailedEvent) error {
	//		fmt.Println(observed.ErrorClass)
	//		return nil
	//	})
	//	if err != nil {
	//		return err
	//	}
	//	defer stop()
	Failed = event.NewTopic[FailedEvent]("mail.failed")
)
View Source
var ErrInvalidMessage = errors.New("invalid mail message")

ErrInvalidMessage indicates that a Message cannot be submitted.

Validation errors wrap ErrInvalidMessage so callers can classify them with errors.Is without inspecting diagnostic text. The error itself does not say whether a separate, earlier submission was accepted or delivered.

Example:

err := mail.NewMessage(mail.Recipients{}, mail.Body{Text: "Hello."}).Err()
if errors.Is(err, mail.ErrInvalidMessage) {
	fmt.Println("correct the message before sending")
}

Functions

func CheckSend

func CheckSend(ctx context.Context, message Message) error

CheckSend performs the checks every Driver makes before any I/O: it returns an error wrapping ctx.Err() when ctx is done, and the error from Message.Validate when message is invalid. The context must be nonnil. This pure preflight applies no defaults and does not submit anything; drivers call it before their provider I/O.

Example:

if err := mail.CheckSend(ctx, message); err != nil {
	return mail.Receipt{}, err
}

func EncodeMIME

func EncodeMIME(message Message, messageID string) ([]byte, error)

EncodeMIME validates message and serializes it as an RFC 5322 MIME message. BCC recipients are intentionally excluded from the visible message headers. Bodies are quoted-printable encoded, which keeps CRLF line endings and lines within the SMTP limit. Attachment media-type parameters are preserved, except that the "name" parameter uses Attachment.Filename, matching Content-Disposition's filename. Invalid attachment metadata, including values that cannot be formatted as MIME, returns an error wrapping ErrInvalidMessage and no output bytes. The message must include From; mailer defaults are not applied here. Successful calls return newly owned bytes, independent of message and other encodings. The output contains message content and must be handled accordingly.

messageID must be an uncommented, unfolded modern RFC 5322 msg-id: angle brackets enclosing a dot-atom left side, @, and a dot-atom or bracketed no-fold-literal right side. Supplied IDs are preserved verbatim; empty IDs, whitespace, comments, obsolete quoted forms, and invalid syntax return ErrInvalidMessage and no bytes. Domain ownership is not verified.

Every emitted physical line must fit within 998 bytes excluding CRLF. Longer lines return ErrInvalidMessage and no bytes. Existing encoded-word/address folding is retained, but oversized plain headers are rejected rather than rewriting caller content or metadata. Related multipart containers declare the actual root media type, including multipart/alternative when the message contains both text and HTML bodies.

Example:

message := mail.NewMessage(mail.Recipients{
	To: []mail.Address{{Email: "reader@example.com"}},
}, mail.Body{Text: "Notes attached."}, func(letter *mail.MessageBuilder) {
	letter.From(mail.Address{Email: "sender@example.com"})
	letter.Attachments(mail.Attachment{
		Filename: "notes.txt", ContentType: "text/plain; charset=UTF-8",
		Data: []byte("meeting notes"),
	})
})
contents, err := mail.EncodeMIME(message, "<notes@example.com>")
if err != nil {
	return err
}
_ = contents

func NewMessageID

func NewMessageID(domain string) (string, error)

NewMessageID builds a randomized Message-ID with 128 bits of random identity. domain must be RFC 5322 dot-atom-text or a bracketed no-fold-literal. Raw IPv6 addresses use [IPv6:address] notation; other accepted domain bytes are preserved verbatim. The tag avoids the untagged IPv6 form rejected by Go's mailbox parser. Empty input, empty dot components, whitespace, controls, and other malformed syntax return an empty ID and ErrInvalidMessage. This validates outbound syntax, not DNS, domain ownership, global uniqueness, or provider-specific limits. EncodeMIME separately checks the physical-line limit; entropy errors propagate.

Example:

id, err := mail.NewMessageID("mail.example.com")
if err != nil {
	return err
}
contents, err := mail.EncodeMIME(message, id)
if err != nil {
	return err
}
_ = contents

Types

type Address

type Address struct {
	// Name is the optional human-readable display name. Empty omits the name;
	// CR or LF is invalid when the address is used in a message.
	//
	// Example:
	//
	//	address := mail.Address{Name: "Support", Email: "support@example.com"}
	//	_ = address.Name
	Name string

	// Email is the required bare mailbox address, without a display name.
	// Message validation rejects empty, malformed, or CR/LF-bearing values.
	//
	// Example:
	//
	//	address := mail.Address{Email: "support@example.com"}
	//	_ = address.Email
	Email string
}

Address identifies a mailbox and its optional display name. It contains only scalar strings; NewMessage validates destination addresses and snapshots the surrounding recipient lists. An empty address is not a valid destination.

Example:

address := mail.Address{Name: "Support", Email: "support@example.com"}
_ = address.String()

func (Address) String

func (address Address) String() string

String renders the mailbox using net/mail's RFC 5322 quoting and name encoding. It does not validate the address; NewMessage checks addresses before submission. The returned string can contain personal data and is not a telemetry label.

Example:

address := mail.Address{Name: "Doe, Jane", Email: "jane@example.com"}
fmt.Println(address.String()) // "Doe, Jane" <jane@example.com>

type Attachment

type Attachment struct {
	// Filename is the required attachment filename presented to recipients.
	// EncodeMIME uses it for both Content-Type's name parameter and
	// Content-Disposition's filename, overriding a name supplied in ContentType.
	// Provider API mappings can impose their own attachment restrictions.
	// EncodeMIME rejects over-limit physical header lines instead of truncating
	// the filename or rewriting its parameter encoding.
	//
	// Example:
	//
	//	_ = mail.Attachment{
	//		Filename:    "notes.txt",
	//		ContentType: "text/plain",
	//		Data:        []byte("notes"),
	//	}
	Filename string

	// ContentType is the required MIME media type, optionally with parameters.
	// Empty is invalid; there is no application/octet-stream fallback.
	// EncodeMIME preserves parameters except name, which comes from Filename.
	// If MIME formatting fails, EncodeMIME returns an error wrapping
	// ErrInvalidMessage and no bytes.
	// Provider API drivers can map media types differently from EncodeMIME.
	//
	// Example:
	//
	//	_ = mail.Attachment{
	//		Filename:    "notes.txt",
	//		ContentType: "text/plain; charset=UTF-8",
	//		Data:        []byte("meeting notes"),
	//	}
	ContentType string

	// Data contains the required unencoded payload; an empty slice is invalid.
	// Construction and Attachments getters copy these bytes independently.
	//
	// Example:
	//
	//	file := mail.Attachment{Filename: "notes.txt", ContentType: "text/plain", Data: []byte("notes")}
	//	_ = len(file.Data)
	Data []byte

	// Disposition selects regular or inline placement. Empty is normalized to
	// AttachmentDispositionAttachment on the message's copied record; unknown
	// nonempty values are invalid. Inline placement requires ContentID.
	//
	// Example:
	//
	//	file := mail.Attachment{
	//		Filename: "logo.png", ContentType: "image/png", Data: []byte("image"),
	//		Disposition: mail.AttachmentDispositionInline, ContentID: "logo",
	//	}
	//	_ = file.Disposition
	Disposition AttachmentDisposition

	// ContentID identifies inline attachment content.
	//
	// ContentID is required when Disposition is AttachmentDispositionInline and
	// must otherwise be empty. CR, LF, spaces and angle brackets are rejected;
	// supply the bare identifier, not a cid: URL or a bracketed header value.
	//
	// Example:
	//
	//	file := mail.Attachment{
	//		Filename: "logo.png", ContentType: "image/png", Data: []byte("image"),
	//		Disposition: mail.AttachmentDispositionInline, ContentID: "logo",
	//	}
	//	body := mail.Body{HTML: `<img src="cid:` + file.ContentID + `">`}
	//	_ = body
	ContentID string
}

Attachment is one MIME attachment.

Inline attachments require ContentID. HTML content references them with a "cid:" URL, for example: <img src="cid:company-logo">. NewMessage copies the attachment records and bytes; later edits to the input record or Data do not change a published message. Empty payloads are invalid.

Example:

file := mail.Attachment{Filename: "notes.txt", ContentType: "text/plain", Data: []byte("notes")}
message := mail.NewMessage(recipients, mail.Body{Text: "Notes attached."}, func(letter *mail.MessageBuilder) {
	letter.Attachments(file)
})
if err := message.Err(); err != nil {
	return err
}

type AttachmentDisposition

type AttachmentDisposition string

AttachmentDisposition determines how an attachment is represented in MIME. Empty input selects AttachmentDispositionAttachment. Message construction normalizes this default without changing the caller's attachment records.

Example: _ = mail.Attachment{Disposition: mail.AttachmentDispositionInline}

const (
	// AttachmentDispositionAttachment sends data as a downloadable attachment.
	//
	// Example: _ = mail.Attachment{Disposition: mail.AttachmentDispositionAttachment}
	AttachmentDispositionAttachment AttachmentDisposition = "attachment"

	// AttachmentDispositionInline embeds data in an HTML email through a CID.
	//
	// Example: _ = mail.Attachment{Disposition: mail.AttachmentDispositionInline, ContentID: "logo"}
	AttachmentDispositionInline AttachmentDisposition = "inline"
)

type Body

type Body struct {
	// Text is the plain-text representation; empty is valid when HTML is set.
	//
	// Example:
	//
	//	body := mail.Body{Text: "Hello."}
	Text string
	// HTML is the HTML representation; empty is valid when Text is set.
	//
	// Example:
	//
	//	body := mail.Body{HTML: "<p>Hello.</p>"}
	HTML string
}

Body supplies the required message content to NewMessage. At least one representation must be nonempty; HTML is not generated from Text or vice versa.

Example:

message := mail.NewMessage(recipients, mail.Body{Text: "Hello.", HTML: "<p>Hello.</p>"})
_ = message.Err()

type Builder

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

Builder configures the defaults of a Mailer before publication. Methods return the same draft. New copies owned reply-to addresses, not services. Retaining a draft cannot change the published mailer or its Config snapshots.

Example:

mailer := mail.New(driver, func(mailer *mail.Builder) {
	mailer.From(mailAddress)
})
_ = mailer.Config()

func (*Builder) Events

func (mailer *Builder) Events(events *event.Bus) *Builder

Events selects the shared bus receiving Sent and Failed after the outcome is known. Nil publishes nothing; listeners cannot change the send outcome. A driver panic propagates without publishing either event. Failure notifications contain only a bounded ErrorClass and counts, not the diagnostic error returned by Send, addresses, or message contents.

Example:

mail.New(driver, func(mailer *mail.Builder) {
	mailer.Events(nil)
})

func (*Builder) From

func (mailer *Builder) From(from Address) *Builder

From sets the sender used when a message omits it. Later calls replace it; an empty address restores the empty default and Send's normal validation. Address validation remains deferred to Send after message defaults apply.

Example:

mail.New(driver, func(mailer *mail.Builder) {
	mailer.From(sender)
})

func (*Builder) ReplyTo

func (mailer *Builder) ReplyTo(replyTo ...Address) *Builder

ReplyTo replaces the reply-to defaults used when a message omits them. Empty input clears them. The input and completed publication each own their slice; later input edits or retained draft changes do not affect the Mailer.

Example:

mail.New(driver, func(mailer *mail.Builder) {
	mailer.ReplyTo(support)
})

func (*Builder) Telemetry

func (mailer *Builder) Telemetry(instrumentation *telemetry.Telemetry) *Builder

Telemetry selects the shared service that records sends. Nil follows telemetry.Default per operation, including changes after construction. No addresses, subjects, contents or receipt values are recorded.

Example:

mail.New(driver, func(mailer *mail.Builder) {
	mailer.Telemetry(nil)
})

type BuilderFunc

type BuilderFunc = func(*Builder)

BuilderFunc edits New's fresh construction draft synchronously, once, in callback order. Nil entries panic; expanded nil or empty slices omit edits. Publication detaches owned settings, not the driver or reporting services.

Example:

policy := mail.BuilderFunc(func(mailer *mail.Builder) {
	mailer.From(mail.Address{Email: "sender@example.com"})
})
mailer := mail.New(driver, policy)
_ = mailer.Config().From

type Config

type Config struct {
	// From reports the sender used when a message omits it. The initial value
	// is empty, requiring an explicit message sender before submission.
	//
	// Example:
	//
	//	defaults := mail.New(driver).Config()
	//	_ = defaults.From.Email
	From Address

	// ReplyTo reports defaults for messages without explicit reply addresses.
	// It is initially empty. Config returns an independent slice; editing it
	// cannot reconfigure the mailer.
	//
	// Example:
	//
	//	defaults := mail.New(driver).Config()
	//	_ = len(defaults.ReplyTo)
	ReplyTo []Address

	// Telemetry receives the span and metrics of every [Mailer.Send]. Nil uses
	// [telemetry.Default], resolved each time a message is sent, so calling
	// [telemetry.SetDefault] after [New] still takes effect.
	// The service is shared, not cloned with the reporting record.
	//
	// Example:
	//
	//	defaults := mail.New(driver).Config()
	//	_ = defaults.Telemetry // nil follows telemetry.Default per Send.
	Telemetry *telemetry.Telemetry

	// Events reports the shared bus receiving Sent and Failed. Nil, the
	// initial value, publishes nothing. Failure events retain only bounded
	// classifications; Send separately returns original diagnostic errors.
	//
	// Example:
	//
	//	defaults := mail.New(driver).Config()
	//	_ = defaults.Events // nil disables notifications.
	Events *event.Bus
}

Config reports the completed sender defaults and shared reporting services of a Mailer. Obtain it from Mailer.Config, which copies ReplyTo. This record is not accepted by construction; configure New through Builder.

Example:

mailer := mail.New(driver)
defaults := mailer.Config()
_ = defaults.From

type Driver

type Driver interface {
	// Send submits a completed message and returns an opaque acceptance receipt.
	// CheckSend rejects invalid input or a done context before I/O. Acceptance
	// never establishes final recipient delivery; the caller owns retry policy.
	//
	// Example:
	//
	//	receipt, err := driver.Send(ctx, message)
	//	if err != nil {
	//		return err
	//	}
	//	_ = receipt.ID
	Send(ctx context.Context, message Message) (Receipt, error)
}

Driver submits transactional email messages.

Message values are immutable and may be retained safely. Their slice getters return detached address lists, attachment records and payload bytes owned by the caller of the getter; changing those results cannot alter the message. A successful Send confirms driver acceptance, not final recipient delivery.

Send performs CheckSend before any I/O: an invalid message yields an error wrapping ErrInvalidMessage, and a done ctx yields an error wrapping ctx.Err(); either way nothing is submitted. Drivers do not apply Config defaults; Mailer does.

Example:

receipt, err := driver.Send(ctx, message)
if err != nil {
	return err
}
_ = receipt.ID

type FailedEvent

type FailedEvent struct {
	// ErrorClass is context.Canceled, context.DeadlineExceeded,
	// mail.ErrInvalidMessage, or "error" for any other failure, in that priority
	// order. It never includes diagnostic text, arbitrary type names, or causes.
	// These classes do not establish whether a provider accepted a submission.
	//
	// Example:
	//
	//	observed := mail.FailedEvent{ErrorClass: "mail.ErrInvalidMessage"}
	//	_ = observed.ErrorClass
	ErrorClass string

	// Recipients counts the attempted To, CC, and BCC entries. It can be zero
	// for an invalid declaration and never contains an address itself.
	//
	// Example:
	//
	//	observed := mail.FailedEvent{Recipients: 1}
	//	_ = observed.Recipients
	Recipients int

	// Attachments counts attempted regular and inline attachments together.
	// The records and payload bytes are excluded from this observation.
	//
	// Example:
	//
	//	observed := mail.FailedEvent{Attachments: 1}
	//	_ = observed.Attachments
	Attachments int
}

FailedEvent observes a returned validation or driver failure, not proof that delivery is impossible. Only a bounded classification and counts are retained; Mailer.Send separately returns the original error with its causes intact.

Example:

stop, err := bus.Listen(mail.Failed, func(ctx context.Context, observed mail.FailedEvent) error {
	fmt.Println(observed.ErrorClass)
	return nil
})
if err != nil {
	return err
}
defer stop()
Example

ExampleFailedEvent demonstrates privacy-safe observations while the caller retains the original failure for application-owned handling.

package main

import (
	"context"
	"errors"
	"fmt"

	"arkoren.dev/core/event"
	"arkoren.dev/core/service/mail"
	"arkoren.dev/core/service/mail/mailtest"
)

func main() {
	bus := event.New()

	stop, err := bus.Listen(mail.Failed, func(_ context.Context, observed mail.FailedEvent) error {
		fmt.Println(observed.ErrorClass, observed.Recipients)

		return nil
	})

	if err != nil {
		fmt.Println(err)

		return
	}

	defer stop()
	driver := mailtest.New()
	cause := errors.New("private SMTP recipient diagnostic")
	driver.FailNext(cause)

	mailer := mail.New(driver, func(mailer *mail.Builder) {
		mailer.Events(bus)
		mailer.From(mail.Address{Email: "sender@example.com"})
	})

	message := mail.NewMessage(mail.Recipients{
		BCC: []mail.Address{{Email: "hidden@example.com"}},
	}, mail.Body{Text: "Hello."})

	_, err = mailer.Send(context.Background(), message)
	fmt.Println(errors.Is(err, cause))
}
Output:
error 1
true

type Mailer

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

Mailer completes defaults and validates immutable Message values before submitting them to a shared Driver. It owns no lifecycle, retry policy, or delivery tracking. Settings are fixed by New; Config is reporting-only.

Example:

mailer := mail.New(driver, func(mailer *mail.Builder) {
	mailer.From(mail.Address{Email: "sender@example.com"})
})
_ = mailer.Config().From

func New

func New(driver Driver, configure ...BuilderFunc) *Mailer

New creates a Mailer backed by driver. Construction policies set the sender values applied to messages that omit them and the telemetry. When telemetry is enabled every Mailer.Send with a nonnil context emits one "mail send" client span and the arkoren.mail.operations and arkoren.mail.operation.duration metrics, and costs nothing otherwise. Metrics count attempts, including driver panics, not confirmed acceptance. Addresses, subject, body, attachments, headers and the receipt are never recorded; the span carries the operation, recipient and attachment counts, and the class of a returned error, not a panic value.

mailer := mail.New(driver, func(mailer *mail.Builder) {
	mailer.Telemetry(app.Telemetry())
})

Construction callbacks run directly once, synchronously in order on one fresh draft. Nil entries panic; expanded nil or empty slices omit edits. Publication detaches owned settings, not live dependencies or captures.

func (*Mailer) Config

func (mailer *Mailer) Config() Config

Config returns the completed Mailer defaults with an independent ReplyTo slice. Telemetry and event services remain shared. It is a reporting record, not a constructor input; use Builder policies to configure a mailer.

Example:

mailer := mail.New(driver)
defaults := mailer.Config()
_ = defaults.From

func (*Mailer) Driver

func (mailer *Mailer) Driver() Driver

Driver returns the original shared backend, including any wrapping driver. It can be nil if New received nil. Direct use bypasses facade defaults, telemetry, and events, not the driver's CheckSend obligation or lifecycle.

Example:

backend := mail.New(driver).Driver()
_ = backend

func (*Mailer) DriverAs

func (mailer *Mailer) DriverAs[T any]() (T, bool)

DriverAs returns the first driver of type T in the chain of the underlying driver. A driver that wraps another exposes it with an Unwrap() Driver method, so wrappers such as prefixing or tracing drivers do not hide the concrete driver. No match returns T's zero value and false; neither the facade nor a wrapper is removed or reconfigured by inspection.

Example:

backend, ok := mail.New(driver).DriverAs[mail.Driver]()
if ok {
	_ = backend
}

func (*Mailer) Send

func (mailer *Mailer) Send(ctx context.Context, message Message) (receipt Receipt, err error)

Send completes unset message defaults in a local copy, validates the resulting Message, and delegates submission to Driver without replaying construction callbacks. The original message remains unchanged. When Builder.Events is set, returned validation or driver errors publish Failed; driver acceptance publishes Sent, not confirmation of recipient delivery. A nil ctx fails before telemetry or events. Failed notifications carry only a bounded class; the returned error retains original validation and provider causes for errors.Is and errors.As.

A driver panic propagates unchanged without publishing either outcome. Telemetry still closes the mailer's own span and records attempt metrics, without ending the caller's span, classifying the panic or recording its value.

Example:

events := event.New()
mailer := mail.New(driver, func(mailer *mail.Builder) {
	mailer.Events(events)
})
receipt, err := mailer.Send(ctx, message)
if err != nil {
	return err
}
_ = receipt.ID

type Message

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

Message is an immutable transactional email declaration. Construct it with NewMessage; its zero value is invalid. Slice getters return detached copies, including attachment data. Copies of Message safely share private storage.

Example:

message := mail.NewMessage(mail.Recipients{
	To: []mail.Address{{Email: "person@example.com"}},
}, mail.Body{Text: "Hello."})
if err := message.Err(); err != nil {
	return err
}

func NewMessage

func NewMessage(recipients Recipients, body Body, configure ...MessageBuilderFunc) Message

NewMessage snapshots recipients and body, then invokes configure directly once, synchronously in order on one fresh draft. Nil entries and application panics propagate; expanded nil or empty slices omit edits. Positional validation runs first, recipients before body. The first domain error stays sticky even when a later optional setting replaces its value. Publication detaches draft storage. Omitted From is valid here because Mailer.Send may supply it; Message.Validate requires a completed sender before submission. Construction performs no I/O.

Example:

message := mail.NewMessage(mail.Recipients{
	To: []mail.Address{{Email: "person@example.com"}},
}, mail.Body{Text: "Hello."}, func(letter *mail.MessageBuilder) {
	letter.Subject("Welcome")
})
if err := message.Err(); err != nil {
	return err
}

func (Message) Attachments

func (message Message) Attachments() []Attachment

Attachments returns detached attachment records, including independent Data bytes for each one. Modifying the returned records or bytes is safe.

Example:

files := message.Attachments()
_ = len(files)

func (Message) BCC

func (message Message) BCC() []Address

BCC returns detached hidden recipients in construction order. Drivers must deliver to them without exposing them in visible headers.

Example:

hidden := message.BCC()
_ = len(hidden)

func (Message) CC

func (message Message) CC() []Address

CC returns detached visible-copy recipients. Their order matches construction; editing or appending to the result does not change the message.

Example:

copies := message.CC()
_ = len(copies)

func (Message) Err

func (message Message) Err() error

Err returns the first construction error, wrapping ErrInvalidMessage, or nil for a valid declaration. Unlike Validate, it permits an omitted From. The zero Message is invalid because it has no recipients.

Example:

if err := message.Err(); err != nil {
	return err
}

func (Message) From

func (message Message) From() Address

From returns the sender, or the zero address when omitted before completion. It contains only strings and can be changed without affecting the message.

Example:

sender := message.From()
_ = sender.Email

func (Message) HTMLBody

func (message Message) HTMLBody() string

HTMLBody returns the HTML representation unchanged. It may be empty for a text-only declaration; no conversion from text is performed.

Example:

html := message.HTMLBody()
_ = html

func (Message) ReplyTo

func (message Message) ReplyTo() []Address

ReplyTo returns detached reply destinations in construction order. Empty means Mailer.Send may supply its defaults; modifying the result is safe.

Example:

replies := message.ReplyTo()
_ = len(replies)

func (Message) Subject

func (message Message) Subject() string

Subject returns the optional subject without MIME encoding. Empty is valid; invalid declarations can still be inspected, so check Err before use.

Example:

subject := message.Subject()
_ = subject

func (Message) TextBody

func (message Message) TextBody() string

TextBody returns the plain-text representation unchanged. It may be empty for an HTML-only declaration; no conversion from HTML is performed.

Example:

text := message.TextBody()
_ = text

func (Message) To

func (message Message) To() []Address

To returns a detached primary-recipient slice. Empty lists return nil when constructed from nil; editing the result never changes the message.

Example:

recipients := message.To()
_ = len(recipients)

func (Message) Validate

func (message Message) Validate() error

Validate checks the declaration and completed sender and reply-to addresses without I/O. Use Err before mailer default completion; direct drivers and MIME encoding require Validate. Errors wrap ErrInvalidMessage.

Example:

if err := message.Validate(); err != nil {
	return err
}

type MessageBuilder

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

MessageBuilder edits optional message settings during NewMessage. Required recipients and content are positional and cannot be replaced by a callback. Retaining this draft cannot change a published Message.

Example:

message := mail.NewMessage(recipients, body, func(letter *mail.MessageBuilder) {
	letter.Subject("Welcome").From(mail.Address{Email: "sender@example.com"})
})
_ = message.Err()

func (*MessageBuilder) Attachments

func (letter *MessageBuilder) Attachments(attachments ...Attachment) *MessageBuilder

Attachments replaces and deeply snapshots the attachment records and payloads. Empty clears the list. Invalid MIME metadata or empty data records an error.

Example:

message := mail.NewMessage(recipients, body, func(letter *mail.MessageBuilder) {
	letter.Attachments(mail.Attachment{
		Filename: "report.txt", ContentType: "text/plain", Data: []byte("report"),
	})
})
_ = message.Attachments()

func (*MessageBuilder) From

func (letter *MessageBuilder) From(from Address) *MessageBuilder

From replaces the explicit sender and validates it immediately. Omit this setting to use mailer defaults; an explicitly empty address is invalid.

Example:

message := mail.NewMessage(recipients, body, func(letter *mail.MessageBuilder) {
	letter.From(mail.Address{Email: "sender@example.com"})
})
_ = message.Err()

func (*MessageBuilder) ReplyTo

func (letter *MessageBuilder) ReplyTo(addresses ...Address) *MessageBuilder

ReplyTo replaces and snapshots reply destinations. Empty clears the setting, allowing mailer defaults. Invalid addresses remain errors after replacement.

Example:

message := mail.NewMessage(recipients, body, func(letter *mail.MessageBuilder) {
	letter.ReplyTo(mail.Address{Email: "support@example.com"})
})
_ = message.ReplyTo()

func (*MessageBuilder) Subject

func (letter *MessageBuilder) Subject(subject string) *MessageBuilder

Subject replaces the optional subject. Empty is valid; CR or LF records a sticky domain error to prevent injection into message headers. Construction imposes no provider length limit. EncodeMIME rejects a physical header line over 998 bytes if the existing encoded-word folding cannot fit it; it does not truncate or rewrite plain subject text to force acceptance.

Example:

message := mail.NewMessage(recipients, body, func(letter *mail.MessageBuilder) {
	letter.Subject("Welcome")
})
_ = message.Subject()

type MessageBuilderFunc

type MessageBuilderFunc = func(*MessageBuilder)

MessageBuilderFunc configures optional settings on one construction draft. Callbacks run directly once in order, including for invalid declarations.

Example:

var policy mail.MessageBuilderFunc = func(letter *mail.MessageBuilder) {
	letter.Subject("Welcome")
}
message := mail.NewMessage(recipients, body, policy)
_ = message.Err()

type Receipt

type Receipt struct {
	// ID identifies the accepted submission when supplied; it can be empty.
	// It is not a delivery confirmation or an idempotency key for retries.
	//
	// Example:
	//
	//	receipt := mail.Receipt{ID: "submission-123"}
	//	_ = receipt.ID
	ID string
}

Receipt identifies a submission accepted by a driver.

ID is opaque. SMTP drivers return the generated RFC 5322 Message-ID. API drivers return the provider submission identifier when available. The record contains scalar data owned by the caller, not a delivery status.

Example:

receipt, err := mailer.Send(ctx, message)
if err != nil {
	return err
}
_ = receipt.ID

type Recipients

type Recipients struct {
	// To contains primary recipients. NewMessage snapshots the slice.
	//
	// Example:
	//
	//	recipients := mail.Recipients{To: []mail.Address{{Email: "person@example.com"}}}
	To []Address
	// CC contains visible carbon-copy recipients, independently of To.
	//
	// Example:
	//
	//	recipients := mail.Recipients{CC: []mail.Address{{Email: "copy@example.com"}}}
	CC []Address
	// BCC contains hidden recipients, never exposed in visible MIME headers.
	// A message may have only BCC recipients.
	//
	// Example:
	//
	//	recipients := mail.Recipients{BCC: []mail.Address{{Email: "hidden@example.com"}}}
	BCC []Address
}

Recipients supplies the required delivery destinations to NewMessage. At least one address across the three lists is required; construction copies them.

Example:

recipients := mail.Recipients{To: []mail.Address{{Email: "person@example.com"}}}
message := mail.NewMessage(recipients, mail.Body{Text: "Hello."})
_ = message.Err()

type SentEvent

type SentEvent struct {
	// Receipt identifies the accepted submission, not a delivered message.
	// The opaque value is supplied by the driver; it can be empty.
	//
	// Example:
	//
	//	observed := mail.SentEvent{Receipt: mail.Receipt{ID: "submission-123"}}
	//	_ = observed.Receipt.ID
	Receipt Receipt

	// Recipients counts To, CC, and BCC entries, including repeated addresses.
	// It does not disclose which addresses received the submission.
	//
	// Example:
	//
	//	observed := mail.SentEvent{Recipients: 2}
	//	_ = observed.Recipients
	Recipients int

	// Attachments counts regular and inline attachments together. Zero means
	// the submitted message contained no attachments.
	//
	// Example:
	//
	//	observed := mail.SentEvent{Attachments: 1}
	//	_ = observed.Attachments
	Attachments int
}

SentEvent observes driver acceptance, not recipient delivery. It contains submission metadata and counts, never message content or destination addresses.

Example:

stop, err := bus.Listen(mail.Sent, func(ctx context.Context, observed mail.SentEvent) error {
	fmt.Println(observed.Recipients)
	return nil
})
if err != nil {
	return err
}
defer stop()

Directories

Path Synopsis
internal
mime
Package mime renders validated mail projections without importing the mail facade.
Package mime renders validated mail projections without importing the mail facade.
Package mailtest provides test support for mail.Driver implementations and for code that sends mail.
Package mailtest provides test support for mail.Driver implementations and for code that sends mail.
Package slogmail provides a development mail.Driver that logs each message to a log/slog.Logger instead of sending it.
Package slogmail provides a development mail.Driver that logs each message to a log/slog.Logger instead of sending it.

Jump to

Keyboard shortcuts

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