mailer

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 10 Imported by: ? 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

mailer - basic mailer, with json persistence support

Release Test Go Reference Go Report Card codecov

Requires Go 1.26+

go get github.com/abagile/tokyo3-mailer

Usage

Send an email
m := &mailer.Mailer{
    SmtpHost:          "smtp.example.com",
    SmtpPort:          587,
    SmtpUsername:      "user@example.com",
    SmtpPassword:      "secret",
    SmtpSenderAddress: "user@example.com",
    SmtpSenderName:    "My App",
    SmtpTLSPortPolicy: "opportunistic", // "", "opportunistic", or "mandatory"
    SmtpTimeout:       30 * time.Second, // zero uses the library default
}

msg := &mailer.Message{
    To:      []*mailer.Recipient{{Name: "Alice", Address: "alice@example.com"}},
    Cc:      []*mailer.Recipient{{Address: "cc@example.com"}},
    Subject: "Hello",
    Content: "Plain-text body.",
    HTML:    "<p>HTML body.</p>",
}

if err := m.Send(msg); err != nil {
    log.Fatal(err)
}

Use SendContext when delivery should honor caller cancellation or a deadline:

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

if err := m.SendContext(ctx, msg); err != nil {
    log.Fatal(err)
}

SmtpTimeout configures SMTP connection and I/O deadlines. It must be positive when set; zero keeps the underlying mail client's default timeout. The shorter of a context deadline and the configured connection timeout controls dialing.

The From field on a Message overrides the mailer-level sender for that message:

msg.From = &mailer.Recipient{Name: "Other Sender", Address: "other@example.com"}
Parse an address string

ParseAddress splits an RFC 5322 string into a Recipient:

r, err := mailer.ParseAddress("Alice <alice@example.com>")
// r.Name    == "Alice"
// r.Address == "alice@example.com"

r, err = mailer.ParseAddress("alice@example.com")
// r.Name    == ""
// r.Address == "alice@example.com"

JSON persistence

Message serialises to and from JSON, which lets you queue messages in a database, file, or message queue and send them later — without a live SMTP connection at enqueue time.

Saving
msg := &mailer.Message{
    To:      []*mailer.Recipient{{Name: "Alice", Address: "alice@example.com"}},
    Subject: "Report",
    Content: "See attached.",
    Attachments: []*mailer.Attachment{
        {Path: "/tmp/report.pdf"}, // file read at save time
    },
}

var buf bytes.Buffer
if err := msg.SaveJSON(&buf); err != nil {
    log.Fatal(err)
}

SaveJSON reads any file-path attachments at call time and encodes their content as base64 inside the JSON. Messages using path-backed or in-memory attachments are therefore self-contained. The path field is cleared and only content is stored:

{
  "to": [{"name": "Alice", "address": "alice@example.com"}],
  "subject": "Report",
  "content": "See attached.",
  "attachments": [
    {
      "name": "report.pdf",
      "content": "JVBERi0xLjQK..."
    }
  ]
}
Loading and sending
msg, err := mailer.LoadJSON(&buf)
if err != nil {
    log.Fatal(err)
}
if err := m.Send(msg); err != nil {
    log.Fatal(err)
}

Or in one step from raw bytes:

if err := m.SendJSON(data); err != nil {
    log.Fatal(err)
}

For context-aware queued delivery, use SendJSONContext(ctx, data).

Attachment rules

Attachment sources take precedence in this order: Content, Path, then Reference.

Source Behaviour
Content Bytes are used as-is; no disk or external-store access
Path File is read at Send time or embedded as base64 by SaveJSON
Reference Preserved by SaveJSON and opened only by a resolver-aware send method

Name is optional for path-backed attachments and is derived from the file's base name. In-memory and referenced attachments require a name. A name without content, a path, or a reference represents a valid zero-byte attachment.

Send and SaveJSON reject nil entries in recipient or attachment lists and invalid attachment values.

External attachment references

AttachmentReference identifies content already uploaded to an external store. Store is a logical application-defined store name; references should not contain credentials or arbitrary URLs.

msg.Attachments = []*mailer.Attachment{{
    Name: "report.pdf",
    Reference: &mailer.AttachmentReference{
        Store:       "mail-attachments",
        Key:         "messages/01JXYZ/report.pdf",
        Version:     "v1",
        Size:        104857600,
        Digest:      "sha-256=...",
        ContentType: "application/pdf",
    },
}}

The application remains responsible for upload, retention, and deletion. To send referenced content, provide an AttachmentResolver:

type objectResolver struct {
    store ObjectStore
}

func (r *objectResolver) Open(
    ctx context.Context,
    ref mailer.AttachmentReference,
) (mailer.ResolvedAttachment, error) {
    reader, err := r.store.Open(ctx, ref.Store, ref.Key, ref.Version)
    if err != nil {
        return mailer.ResolvedAttachment{}, err
    }
    return mailer.ResolvedAttachment{
        Reader:      reader,
        Size:        ref.Size,
        ContentType: ref.ContentType,
    }, nil
}

err := m.SendWithResolver(ctx, msg, &objectResolver{store: store})
// Or: m.SendJSONWithResolver(ctx, data, resolver)

The mailer closes resolved readers after delivery. Resolvers should return a seekable reader, usually a temporary file, for larger attachments. This lets the mailer use go-mail's AttachReadSeeker instead of AttachReader, avoiding an additional in-memory copy of the original attachment.

This is not fully constant-memory delivery. The currently used go-mail v0.7.2 base64-encodes each attachment into a complete in-memory MIME buffer before writing it to SMTP. Including MIME line wrapping, that buffer is approximately 1.37 times the original attachment size, with additional capacity and protocol overhead possible. For example, a 100 MiB file requires roughly 137 MiB for its encoded MIME buffer. A temporary-file resolver keeps the original 100 MiB out of application memory but does not eliminate this encoded buffer. Applications should enforce attachment and total-message size limits accordingly.

Send, SendContext, SendJSON, and SendJSONContext do not accept a resolver and therefore cannot send reference-only attachments. They return an attachment "<name>" requires a resolver error instead of accessing external storage. Use SendWithResolver or SendJSONWithResolver when references need to be resolved explicitly. Because attachment source precedence is Content, then Path, then Reference, a reference is ignored when the same attachment also has in-memory content or a path.

Local and NATS Object Store example

example/attachments is a separate Go module so the NATS client and its transitive dependencies do not become dependencies of the core mailer module. The example creates temporary local and NATS stores, publishes one object to each, serialises their references, and resolves both during SMTP delivery.

Start NATS with JetStream and an SMTP test server such as Mailpit, then run:

nats-server -js

cd example/attachments
go run .

Configuration:

Variable Default Purpose
NATS_URL nats://localhost:4222 NATS server with JetStream enabled
NATS_CREDS unset Optional NATS user credentials file
SMTP_HOST localhost SMTP server host
SMTP_PORT 1025 SMTP server port
DRY_RUN unset Print reference-only JSON instead of sending SMTP

DRY_RUN still connects to NATS and creates the temporary object because the example uses its returned size and digest in the attachment reference. The NATS resolver streams object chunks to a temporary file and returns that seekable file to the mailer; it does not load the raw object into a byte slice.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	Name      string               `json:"name,omitempty"`
	Path      string               `json:"path,omitempty"`
	Content   []byte               `json:"content,omitempty"`
	Reference *AttachmentReference `json:"reference,omitempty"`
}

Attachment describes content to attach. Content takes precedence over Path, and Path takes precedence over Reference. SaveJSON embeds path-backed content but preserves external references without resolving them.

type AttachmentReference added in v0.2.0

type AttachmentReference struct {
	Store       string `json:"store"`
	Key         string `json:"key"`
	Version     string `json:"version,omitempty"`
	Size        int64  `json:"size,omitempty"`
	Digest      string `json:"digest,omitempty"`
	ContentType string `json:"content_type,omitempty"`
}

AttachmentReference identifies attachment content in an external store. Store is a logical name interpreted by an AttachmentResolver; the reference never contains storage credentials.

type AttachmentResolver added in v0.2.0

type AttachmentResolver interface {
	Open(context.Context, AttachmentReference) (ResolvedAttachment, error)
}

AttachmentResolver opens externally stored attachment content. Upload and lifecycle management remain the caller's responsibility.

type Mailer

type Mailer struct {
	SmtpHost          string
	SmtpPort          int
	SmtpUsername      string
	SmtpPassword      string
	SmtpSenderAddress string
	SmtpSenderName    string
	SmtpTLSPortPolicy string
	SmtpTimeout       time.Duration
}

func (*Mailer) Send

func (m *Mailer) Send(msg *Message) error

func (*Mailer) SendContext added in v0.2.0

func (m *Mailer) SendContext(ctx context.Context, msg *Message) error

func (*Mailer) SendJSON

func (m *Mailer) SendJSON(data []byte) error

func (*Mailer) SendJSONContext added in v0.2.0

func (m *Mailer) SendJSONContext(ctx context.Context, data []byte) error

func (*Mailer) SendJSONWithResolver added in v0.2.0

func (m *Mailer) SendJSONWithResolver(ctx context.Context, data []byte, resolver AttachmentResolver) error

SendJSONWithResolver decodes and sends a message, resolving external attachments with resolver.

func (*Mailer) SendWithResolver added in v0.2.0

func (m *Mailer) SendWithResolver(ctx context.Context, msg *Message, resolver AttachmentResolver) error

SendWithResolver sends a message, resolving external attachments with resolver. The resolver must remain valid for the duration of the call.

type Message

type Message struct {
	To          []*Recipient  `json:"to,omitempty"`
	Cc          []*Recipient  `json:"cc,omitempty"`
	Bcc         []*Recipient  `json:"bcc,omitempty"`
	From        *Recipient    `json:"from,omitempty"`
	Subject     string        `json:"subject,omitempty"`
	Content     string        `json:"content,omitempty"`
	HTML        string        `json:"html,omitempty"`
	Attachments []*Attachment `json:"attachments,omitempty"`
}

func LoadJSON

func LoadJSON(r io.Reader) (*Message, error)

func (*Message) SaveJSON

func (msg *Message) SaveJSON(w io.Writer) error

type Recipient

type Recipient struct {
	Name    string `json:"name,omitempty"`
	Address string `json:"address"`
}

func ParseAddress

func ParseAddress(s string) (*Recipient, error)

type ResolvedAttachment added in v0.2.0

type ResolvedAttachment struct {
	Reader      io.ReadCloser
	Size        int64
	ContentType string
}

ResolvedAttachment is content opened by an AttachmentResolver. Reader is closed by the mailer after sending. Seekable readers avoid in-memory buffering in the underlying mail package.

Directories

Path Synopsis
Package main demonstrates the mailer package.
Package main demonstrates the mailer package.

Jump to

Keyboard shortcuts

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