mail

package
v0.0.0-...-6efe9ac Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package mail provides message construction, MIME attachment rendering, and SMTP sending helpers.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidAddress is returned when an email address cannot be parsed or validated.
	ErrInvalidAddress error = &sentinel{code: knifer.ErrCodeInvalidInput, msg: "mail: invalid address"}
	// ErrInvalidHeader is returned when a header name or value is not safe for SMTP/MIME output.
	ErrInvalidHeader error = &sentinel{code: knifer.ErrCodeInvalidInput, msg: "mail: invalid header"}
	// ErrMissingFrom is returned when a message has no From address.
	ErrMissingFrom error = &sentinel{code: knifer.ErrCodeInvalidInput, msg: "mail: missing from address"}
	// ErrMissingRecipient is returned when a message has no To, Cc, or Bcc recipient.
	ErrMissingRecipient error = &sentinel{code: knifer.ErrCodeInvalidInput, msg: "mail: missing recipient"}
	// ErrMissingBody is returned when a message has no body content.
	ErrMissingBody error = &sentinel{code: knifer.ErrCodeInvalidInput, msg: "mail: missing body"}
	// ErrTLSRequired is returned when the configured security policy requires TLS but TLS is unavailable.
	ErrTLSRequired error = &sentinel{code: knifer.ErrCodeUnsupported, msg: "mail: tls required"}
	// ErrPlainAuth is returned when SMTP AUTH would be sent over a plaintext connection.
	ErrPlainAuth error = &sentinel{code: knifer.ErrCodeUnsupported, msg: "mail: plaintext auth disabled"}
	// ErrAttachmentTooLarge is returned when an attachment exceeds the configured size limit.
	ErrAttachmentTooLarge error = &sentinel{code: knifer.ErrCodeInvalidInput, msg: "mail: attachment too large"}
)

Functions

func QuickSend

func QuickSend(ctx context.Context, account Account, opts ...QuickOption) error

QuickSend creates and sends a message using account defaults plus quick options.

func Send

func Send(ctx context.Context, host string, port int, message *Message, opts ...ClientOption) error

Send sends message through an SMTP server created from host, port, and options.

func SendAccountHTML

func SendAccountHTML(
	ctx context.Context,
	account Account,
	to []string,
	subject string,
	html string,
	opts ...QuickOption,
) error

SendAccountHTML creates and sends an HTML message using account defaults.

func SendAccountText

func SendAccountText(
	ctx context.Context,
	account Account,
	to []string,
	subject string,
	text string,
	opts ...QuickOption,
) error

SendAccountText creates and sends a plain text message using account defaults.

func SendHTML

func SendHTML(ctx context.Context, host string, port int, from string, to []string, subject, html string, opts ...ClientOption) error

SendHTML creates and sends an HTML message.

func SendText

func SendText(ctx context.Context, host string, port int, from string, to []string, subject, text string, opts ...ClientOption) error

SendText creates and sends a plain text message.

Types

type Account

type Account struct {
	Host           string
	Port           int
	Username       string
	Password       string
	Auth           smtp.Auth
	From           string
	FromName       string
	TLSConfig      *tls.Config
	TLSPolicy      TLSPolicy
	AllowPlainAuth bool
	Timeout        time.Duration
	LocalName      string
}

Account stores SMTP server, authentication, and default sender settings.

type Address

type Address struct {
	Name  string
	Email string
}

Address is an RFC 5322 mailbox address.

func NewAddress

func NewAddress(name, email string) (*Address, error)

NewAddress validates and returns a mailbox address.

func ParseAddress

func ParseAddress(value string) (*Address, error)

ParseAddress parses a single mailbox address.

func ParseAddressList

func ParseAddressList(value string) ([]*Address, error)

ParseAddressList parses a comma-separated mailbox address list.

func (*Address) String

func (a *Address) String() string

String formats a for use in message headers.

type Attachment

type Attachment struct {
	Name        string
	ContentType ContentType
	ContentID   string
	Encoding    Encoding
	Size        int64
	Open        func() (io.ReadCloser, error)
	// contains filtered or unexported fields
}

Attachment is a MIME file part.

func NewAttachment

func NewAttachment(name string, content []byte, contentType ContentType) (Attachment, error)

NewAttachment creates an attachment from bytes.

func NewAttachmentFile

func NewAttachmentFile(path string) (Attachment, error)

NewAttachmentFile creates an attachment loaded lazily from path.

func NewAttachmentReader

func NewAttachmentReader(name string, size int64, contentType ContentType, open func() (io.ReadCloser, error)) (Attachment, error)

NewAttachmentReader creates an attachment from a reader opener.

func NewInline

func NewInline(name, contentID string, content []byte, contentType ContentType) (Attachment, error)

NewInline creates an inline attachment from bytes with a Content-ID.

func NewInlineFile

func NewInlineFile(path, contentID string) (Attachment, error)

NewInlineFile creates an inline attachment loaded lazily from path with a Content-ID.

func NewInlineReader

func NewInlineReader(
	name string,
	contentID string,
	size int64,
	contentType ContentType,
	open func() (io.ReadCloser, error),
) (Attachment, error)

NewInlineReader creates an inline attachment from a reader opener with a Content-ID.

type BoundaryGenerator

type BoundaryGenerator func() (string, error)

BoundaryGenerator creates MIME multipart boundaries.

type Charset

type Charset string

Charset identifies a MIME character set.

const (
	// CharsetUTF8 is the default charset used for text parts and encoded words.
	CharsetUTF8 Charset = "UTF-8"
	// CharsetASCII identifies US-ASCII content.
	CharsetASCII Charset = "US-ASCII"
)

func (Charset) String

func (c Charset) String() string

type Client

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

Client sends messages through SMTP.

func NewClient

func NewClient(host string, port int, opts ...ClientOption) (*Client, error)

NewClient creates an SMTP client.

func (*Client) Dial

func (c *Client) Dial(ctx context.Context) (SendCloser, error)

Dial opens a reusable SMTP connection for sending multiple messages.

func (*Client) Send

func (c *Client) Send(ctx context.Context, message *Message) error

Send sends message with context cancellation and configured SMTP security.

type ClientOption

type ClientOption func(*Client) error

ClientOption customizes Client construction.

func WithAllowPlainAuth

func WithAllowPlainAuth(allow bool) ClientOption

WithAllowPlainAuth permits SMTP AUTH without TLS. Prefer TLS instead.

func WithAuth

func WithAuth(username, password string) ClientOption

WithAuth sets SMTP username and password.

func WithDialContext

func WithDialContext(dial DialContextFunc) ClientOption

WithDialContext sets the network dialer.

func WithLocalName

func WithLocalName(name string) ClientOption

WithLocalName sets the HELO/EHLO local name.

func WithSMTPAuth

func WithSMTPAuth(auth smtp.Auth) ClientOption

WithSMTPAuth sets a custom SMTP authentication mechanism.

func WithSenderProvider

func WithSenderProvider(provider SenderProvider) ClientOption

WithSenderProvider sets a custom sender provider, primarily for deterministic tests.

func WithTLSConfig

func WithTLSConfig(config *tls.Config) ClientOption

WithTLSConfig sets the TLS configuration. The value is cloned.

func WithTLSPolicy

func WithTLSPolicy(policy TLSPolicy) ClientOption

WithTLSPolicy sets SMTP TLS behavior.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets a client-wide operation timeout.

type Config

type Config struct {
	Host           string
	Port           int
	Username       string
	Password       string
	Auth           smtp.Auth
	LocalName      string
	TLSConfig      *tls.Config
	TLSPolicy      TLSPolicy
	AllowPlainAuth bool
	Timeout        time.Duration
	DialContext    DialContextFunc
}

Config configures SMTP delivery.

type ContentType

type ContentType string

ContentType identifies a MIME media type.

const (
	// TypeTextPlain is plain text content.
	TypeTextPlain ContentType = "text/plain"
	// TypeTextHTML is HTML content.
	TypeTextHTML ContentType = "text/html"
	// TypeApplicationOctetStream is generic binary content.
	TypeApplicationOctetStream ContentType = "application/octet-stream"
)

func (ContentType) String

func (c ContentType) String() string

type DialContextFunc

type DialContextFunc func(context.Context, string, string) (net.Conn, error)

DialContextFunc dials an SMTP server.

type Encoding

type Encoding string

Encoding identifies a Content-Transfer-Encoding value.

const (
	// EncodingBase64 encodes content using RFC 2045 base64.
	EncodingBase64 Encoding = "base64"
	// EncodingQuotedPrintable encodes content using quoted-printable.
	EncodingQuotedPrintable Encoding = "quoted-printable"
	// Encoding7Bit marks content as 7bit.
	Encoding7Bit Encoding = "7bit"
	// Encoding8Bit marks content as 8bit.
	Encoding8Bit Encoding = "8bit"
)

func (Encoding) String

func (e Encoding) String() string
type Header struct {
	// contains filtered or unexported fields
}

Header stores message headers in insertion order.

func (*Header) Add

func (h *Header) Add(name string, values ...string) error

Add appends a header value.

func (*Header) Set

func (h *Header) Set(name string, values ...string) error

Set replaces all values for name while keeping deterministic order.

func (*Header) Values

func (h *Header) Values(name string) []string

Values returns all values for name.

type Message

type Message struct {
	From         *Address
	EnvelopeFrom string
	To           []*Address
	Cc           []*Address
	Bcc          []*Address
	ReplyTo      []*Address
	Subject      string
	Text         string
	HTML         string
	Headers      Header
	Attachments  []Attachment
	Inlines      []Attachment
	Date         time.Time
	MessageID    string
	Charset      Charset
	Encoding     Encoding
	// contains filtered or unexported fields
}

Message is an email message with text, HTML, inline files, and attachments.

func NewMessage

func NewMessage(opts ...MessageOption) (*Message, error)

NewMessage creates and validates an email message.

func (*Message) Bytes

func (m *Message) Bytes() ([]byte, error)

Bytes renders the message to a byte slice.

func (*Message) Recipients

func (m *Message) Recipients() []string

Recipients returns all SMTP envelope recipients, including Bcc.

func (*Message) Sender

func (m *Message) Sender() string

Sender returns the SMTP envelope sender for MAIL FROM.

func (*Message) Validate

func (m *Message) Validate() error

Validate checks message invariants before rendering or sending.

func (*Message) WriteTo

func (m *Message) WriteTo(w io.Writer) (int64, error)

WriteTo renders the message to w.

type MessageOption

type MessageOption func(*Message) error

MessageOption customizes message construction.

func WithAttachment

func WithAttachment(name string, content []byte, contentType ContentType) MessageOption

WithAttachment appends an attachment from bytes.

func WithAttachmentFile

func WithAttachmentFile(path string) MessageOption

WithAttachmentFile appends an attachment loaded lazily from path.

func WithAttachmentReader

func WithAttachmentReader(name string, size int64, contentType ContentType, open func() (io.ReadCloser, error)) MessageOption

WithAttachmentReader appends an attachment from a reader opener.

func WithBcc

func WithBcc(addresses ...string) MessageOption

WithBcc appends Bcc recipients.

func WithBoundaryGenerator

func WithBoundaryGenerator(generator BoundaryGenerator) MessageOption

WithBoundaryGenerator injects the MIME boundary generator.

func WithCc

func WithCc(addresses ...string) MessageOption

WithCc appends Cc recipients.

func WithCharset

func WithCharset(charset Charset) MessageOption

WithCharset sets the charset used for message text parts and encoded headers.

func WithDate

func WithDate(t time.Time) MessageOption

WithDate sets the Date header value.

func WithEncoding

func WithEncoding(encoding Encoding) MessageOption

WithEncoding sets the transfer encoding used for text parts.

func WithEnvelopeFrom

func WithEnvelopeFrom(address string) MessageOption

WithEnvelopeFrom sets the SMTP envelope sender for MAIL FROM.

func WithFrom

func WithFrom(address string) MessageOption

WithFrom sets the From address.

func WithFromAddress

func WithFromAddress(addr *Address) MessageOption

WithFromAddress sets the From address.

func WithHTML

func WithHTML(html string) MessageOption

WithHTML sets the text/html body.

func WithHeader

func WithHeader(name string, values ...string) MessageOption

WithHeader appends an additional header.

func WithInline

func WithInline(name, contentID string, content []byte, contentType ContentType) MessageOption

WithInline appends an inline file from bytes.

func WithInlineFile

func WithInlineFile(path, contentID string) MessageOption

WithInlineFile appends an inline attachment loaded lazily from path with a Content-ID.

func WithInlineReader

func WithInlineReader(
	name string,
	contentID string,
	size int64,
	contentType ContentType,
	open func() (io.ReadCloser, error),
) MessageOption

WithInlineReader appends an inline file from a reader opener with a Content-ID.

func WithMaxAttachmentBytes

func WithMaxAttachmentBytes(maxBytes int64) MessageOption

WithMaxAttachmentBytes sets the per-attachment size limit. A non-positive value disables the limit.

func WithMessageID

func WithMessageID(id string) MessageOption

WithMessageID sets the Message-ID header without angle brackets.

func WithReplyTo

func WithReplyTo(addresses ...string) MessageOption

WithReplyTo appends Reply-To addresses.

func WithSubject

func WithSubject(subject string) MessageOption

WithSubject sets the Subject header.

func WithText

func WithText(text string) MessageOption

WithText sets the text/plain body.

func WithTo

func WithTo(addresses ...string) MessageOption

WithTo appends To recipients.

type QuickOption

type QuickOption func(*quickConfig) error

QuickOption customizes account-based quick send helpers.

func WithQuickClientOptions

func WithQuickClientOptions(opts ...ClientOption) QuickOption

WithQuickClientOptions appends client options used by QuickSend and account helpers.

func WithQuickMessageOptions

func WithQuickMessageOptions(opts ...MessageOption) QuickOption

WithQuickMessageOptions appends message options used by QuickSend and account helpers.

type SendCloser

type SendCloser interface {
	Sender
	Close() error
}

SendCloser sends multiple messages through a reusable SMTP connection.

type Sender

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

Sender is implemented by SMTP send backends.

type SenderFunc

type SenderFunc func(context.Context, *Message) error

SenderFunc adapts a function into Sender.

func (SenderFunc) Send

func (f SenderFunc) Send(ctx context.Context, message *Message) error

Send sends message.

type SenderProvider

type SenderProvider func(Config) (Sender, error)

SenderProvider creates a sender for a client configuration.

type TLSPolicy

type TLSPolicy int

TLSPolicy controls SMTP transport security.

const (
	// TLSPolicyUnknown uses the package default, currently mandatory STARTTLS.
	TLSPolicyUnknown TLSPolicy = iota
	// TLSMandatoryStartTLS requires STARTTLS before SMTP AUTH or DATA.
	TLSMandatoryStartTLS
	// TLSImplicit uses implicit TLS from the initial connection.
	TLSImplicit
	// TLSOpportunisticStartTLS upgrades when STARTTLS is advertised.
	TLSOpportunisticStartTLS
	// TLSNone disables TLS. AUTH remains disabled unless AllowPlainAuth is set.
	TLSNone
)

Jump to

Keyboard shortcuts

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