mailutil

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 35 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.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAuthFailed = errors.New("authentication failed")

Error matched by a login the server rejected for good: an SMTP AUTH exchange ended by a 5xx reply or an IMAP LOGIN answered NO, temporary failures excluded

View Source
var ErrInsecure = errors.New("connection is not encrypted")

Error of a login refused before any credentials were sent, the connection being unencrypted and plaintext logins not allowed for it

View Source
var ErrNotFound = errors.New("message not found")

Error of a fetch that brought no content back, the message or the section asked for not existing

View Source
var ErrNotSupported = errors.New("not supported by the server")

Error of an operation the server does not offer, such as STARTTLS or an authentication mechanism it lacks

View Source
var ErrReadOnly = errors.New("mailbox is read-only")

Error of a mailbox the server opened for reading only

View Source
var ErrRefused = errors.New("refused by the server")

Error matched by an IMAP command the server answered with NO

Functions

func DecodeHeader

func DecodeHeader(value string) string

Header text with RFC 2047 encoded words decoded to UTF-8: adjacent words in one character set joined before decoding so characters split across them survive, white space between encoded words dropped, base64 without padding accepted, malformed words and other text kept as they are with raw 8 bit text read as UTF-8 or else Windows-1252

func Dial

func Dial(ctx context.Context, network, address string) (net.Conn, error)

Connection over whichever address family answers, IPv4 tried first while the process prefers it

func DialIPv4

func DialIPv4(ctx context.Context, network, address string) (net.Conn, error)

Connection over IPv4 only, each IPv4 address of the host tried in turn

func ParseAddress

func ParseAddress(s string) (*mail.Address, error)

Mailbox of one address such as Name <user@example.com>, its display name decoded from RFC 2047 in any character set; an error for a list, a group or text that is no address

func ParseParams

func ParseParams(value string) (string, map[string]string)

Value and parameters of a structured field such as Content-Type or Content-Disposition, read leniently: value and parameter names lower cased, a comment after the value dropped, quotes removed, RFC 2231 continuations joined and decoded from their character set, an extended value preferred to a plain one of the same name and the first of repeated plain ones kept

Types

type DialFunc

type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)

Function that opens a network connection, the shape of net.Dialer.DialContext

type Field

type Field struct {
	Name  string
	Value string
}

One header field: the name as written and the value with its folding removed, bytes kept as they arrived

type Header []Field

Fields of a message header in the order they appear, names matched without regard to case

func ParseHeader

func ParseHeader(raw []byte) Header

Fields of the header block at the start of raw, read leniently: mbox From lines skipped, continuation lines unfolded, the block ending at a blank line or at the first line that is not a field, fields past the first maxFields left out

func (*Header) Add

func (h *Header) Add(name, value string)

Appends a field, fields of the same name kept before it

func (Header) Get

func (h Header) Get(name string) string

First value of the field with invalid UTF-8 replaced by U+FFFD, empty when the field is absent

func (Header) Lookup

func (h Header) Lookup(name string) (string, bool)

First value of the field as Get gives it and whether the field is present

func (*Header) Set

func (h *Header) Set(name, value string)

Replaces the first field of the name and drops any later ones, or appends the field when there is none

func (Header) Text

func (h Header) Text(name string) string

First value of the field with RFC 2047 encoded words and raw 8 bit text decoded to UTF-8, empty when the field is absent

func (Header) Values

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

Every value of the field in order, invalid UTF-8 replaced by U+FFFD

type IMAP

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

Client of one IMAP4rev1 session, its commands run one at a time

func DialIMAP

func DialIMAP(ctx context.Context, host string, port int, timeout time.Duration, dial DialFunc, tlsConfig *tls.Config) (*IMAP, error)

Session with the server at host and port, over implicit TLS when a configuration is given, its greeting and capabilities read; port 0 means 993 with TLS and 143 without, timeout bounds the connect and each read and write when not zero, and a nil dial means Dial

func (*IMAP) AllowPlaintextLogin

func (s *IMAP) AllowPlaintextLogin()

Lets Login send the user name and password over a connection without TLS, which it refuses otherwise unless the server is on this machine

func (*IMAP) Close

func (s *IMAP) Close() error

Shuts the connection at once, interrupting a command in progress; doing it again does nothing

func (*IMAP) HasCapability

func (c *IMAP) HasCapability(name string) bool

Whether the server advertised the capability, compared without regard to case

func (*IMAP) ID

func (c *IMAP) ID(ctx context.Context, fields map[string]string) (map[string]string, error)

Identifies the client with the RFC 2971 ID command, which the server must advertise, and returns what the server says about itself

func (*IMAP) Login

func (c *IMAP) Login(ctx context.Context, user, password string) error

Logs in with LOGIN, an error matching ErrAuthFailed when the server rejects the credentials and ErrInsecure without sending anything over a connection without TLS unless AllowPlaintextLogin was called or the server is on this machine; user name and password may hold any text but NUL

func (*IMAP) Logout

func (c *IMAP) Logout(ctx context.Context) error

Ends the session with LOGOUT and closes the connection, which is closed even when the command fails

func (*IMAP) Select

func (c *IMAP) Select(ctx context.Context, name string) (*Mailbox, error)

Opens a mailbox for reading and writing, an error matching ErrReadOnly when the server grants reading only; names outside ASCII are sent in modified UTF-7

func (*IMAP) SetMaxLiteral

func (c *IMAP) SetMaxLiteral(n int64)

Sets the largest literal, such as the content of a fetched message, that a response may bring into memory: 128 MiB until set and again for zero or less; a larger one fails its command with a *LiteralTooLargeError, read past and dropped up to 1 GiB so the connection stays usable and closing the connection beyond that

func (*IMAP) StartTLS

func (c *IMAP) StartTLS(ctx context.Context, config *tls.Config) error

Upgrades the session to TLS with STARTTLS, which the server must advertise, and learns the capabilities again over the encrypted connection

func (*IMAP) UIDFetch

func (c *IMAP) UIDFetch(ctx context.Context, uid uint32, items string) ([]byte, error)

Content of the first body section a UID FETCH of the message brings back, the items given in IMAP syntax such as (BODY[]) or (BODY.PEEK[HEADER]), RFC822 being gone from IMAP4rev2; an error matching ErrNotFound when the server returns none for the UID, and a *LiteralTooLargeError when the content is over the SetMaxLiteral limit

func (*IMAP) UIDSearch

func (c *IMAP) UIDSearch(ctx context.Context, criteria string) ([]uint32, error)

UIDs of the messages of the selected mailbox that match the search criteria, such as ALL or UNSEEN, given in IMAP syntax; both the SEARCH answer and the ESEARCH answer of IMAP4rev2 servers are read

func (*IMAP) UIDStore

func (c *IMAP) UIDStore(ctx context.Context, uid uint32, item string, flags ...string) error

Changes the flags of a message with UID STORE, item one of FLAGS, +FLAGS and -FLAGS with or without .SILENT and flags such as \Seen or $Forwarded

type IMAPError

type IMAPError struct {
	Command string // command name, such as LOGIN or UID FETCH
	Status  string // NO or BAD
	Code    string // response code from inside the brackets, such as AUTHENTICATIONFAILED, empty when the server gave none
	Text    string // human readable text of the answer
}

Answer of NO or BAD an IMAP server gave a command

func (*IMAPError) Error

func (e *IMAPError) Error() string

Message with the command, the status, the response code and the text

func (*IMAPError) Is

func (e *IMAPError) Is(target error) bool

Whether the target is ErrRefused and the answer was NO, or ErrAuthFailed and the answer was a NO to LOGIN that does not report a temporary outage

type LiteralTooLargeError

type LiteralTooLargeError struct {
	Size    int64 // octets the server announced, the largest int64 for a count beyond it
	Limit   int64 // largest literal the client keeps
	Drained bool  // whether the literal was read past and dropped, leaving the connection usable; false when it was over 1 GiB and the connection was closed
}

Literal an IMAP server announced that is larger than the client keeps in memory, see SetMaxLiteral

func (*LiteralTooLargeError) Error

func (e *LiteralTooLargeError) Error() string

Message naming the announced size, the limit and whether the connection was closed

type Mailbox

type Mailbox struct {
	Name        string
	Exists      uint32 // messages in the mailbox
	UIDValidity uint32 // UIDVALIDITY the server reported, zero when it gave none
	UIDNext     uint32 // UID the next message will get, zero when the server gave none
}

Selected mailbox with the counters the server reported for it

type Message

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

Parsed message or one part of it: a leaf holding content, or a container of parts

func Parse

func Parse(raw []byte) *Message

MIME tree of a raw message, read as leniently as real mail requires so nothing makes it fail: missing or stray boundaries, absent charsets and malformed header lines are tolerated; the tree reads from raw without copying it and holds at most maxParts parts and maxFields header fields

func (*Message) Body

func (m *Message) Body() []byte

Content of a leaf with its transfer encoding undone, base64, quoted-printable and uuencode read leniently and any other encoding as it is; nil for a container

func (*Message) Charset

func (m *Message) Charset() string

Lower cased charset parameter of the Content-Type field, empty when the field names none

func (*Message) ContentType

func (m *Message) ContentType() string

Lower cased type/subtype of the Content-Type field, the default of the context when the field is absent and text/plain when it is malformed

func (*Message) Disposition

func (m *Message) Disposition() string

Lower cased disposition the Content-Disposition field gives, such as attachment or inline, empty when the field is absent

func (*Message) Filename

func (m *Message) Filename() string

Name of the file the part carries as the sender wrote it, the Content-Disposition filename or else the Content-Type name, decoded from RFC 2231 and RFC 2047 encodings and trimmed, empty when it declares none; it may hold path separators, .. or control characters, so a caller that writes files takes only a cleaned base name from it

func (*Message) IsMultipart

func (m *Message) IsMultipart() bool

Whether the part holds parts: a multipart with boundaries, or a message part holding the message it embeds

func (*Message) Parts

func (m *Message) Parts() []*Message

Children in order, the embedded message alone for a message part, none for a leaf

func (*Message) Text

func (m *Message) Text() string

Content of a leaf decoded from its transfer encoding and its charset to UTF-8, CRLF line ends turned into LF; empty for a container

func (*Message) Walk

func (m *Message) Walk() iter.Seq[*Message]

The message and every part below it, depth first with each container before its parts

type Part

type Part struct {
	Header Header
	// contains filtered or unexported fields
}

Message or MIME part being built for sending: header fields written in their order, then text, binary data or child parts

func NewAttachment

func NewAttachment(filename, contentType string, data []byte) *Part

Attachment part of the data written in base64, its content type application/octet-stream when the one given is empty or malformed, named filename unless that is empty, non ASCII names encoded per RFC 2231 and long ones split into RFC 2231 continuations

func NewMultipart

func NewMultipart() *Part

Empty multipart/mixed container for Attach

func NewText

func NewText(body string) *Part

Plain text part in UTF-8 written quoted-printable, invalid UTF-8 replaced by U+FFFD

func (*Part) Attach

func (p *Part) Attach(sub *Part)

Adds a child part; a part that is not multipart becomes a multipart/mixed container whose first child takes over its content and Content fields

func (*Part) Set

func (p *Part) Set(name, value string)

Gives the header field the value, replacing any of the same name

func (*Part) WriteTo

func (p *Part) WriteTo(w io.Writer) (int64, error)

Writes the part as a whole message with CRLF line ends, a MIME-Version field first unless the header has one

type SMTP

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

Client of one SMTP session, its commands run one at a time

func DialSMTP

func DialSMTP(ctx context.Context, host string, port int, timeout time.Duration, dial DialFunc, tlsConfig *tls.Config) (*SMTP, error)

Session with the server at host and port, over implicit TLS when a configuration is given, its 220 greeting checked; port 0 means 465 with TLS and 25 without, timeout bounds the connect and each read and write when not zero, and a nil dial means Dial

func (*SMTP) AllowPlaintextLogin

func (s *SMTP) AllowPlaintextLogin()

Lets Login send the user name and password over a connection without TLS, which it refuses otherwise unless the server is on this machine

func (*SMTP) Close

func (s *SMTP) Close() error

Shuts the connection at once, interrupting a command in progress; doing it again does nothing

func (*SMTP) Login

func (c *SMTP) Login(ctx context.Context, user, password string) error

Logs in with the first of CRAM-MD5, PLAIN and LOGIN the server advertises and accepts, the next tried when one is rejected; an error matching ErrAuthFailed when every one is, and ErrInsecure without sending anything over a connection without TLS unless AllowPlaintextLogin was called or the server is on this machine

func (*SMTP) Quit

func (c *SMTP) Quit(ctx context.Context) error

Ends the session with QUIT and closes the connection, which is closed even when the command fails

func (*SMTP) SendMessage

func (c *SMTP) SendMessage(ctx context.Context, msg *Part) error

Sends the message from the address of its Sender or From field to every address of its To, Cc and Bcc fields, the Resent- fields instead when it carries one Resent- block, with its Bcc fields left out of what is sent; addresses outside ASCII go through SMTPUTF8 or, for a domain alone, punycode

func (*SMTP) StartTLS

func (c *SMTP) StartTLS(ctx context.Context, config *tls.Config) error

Upgrades the session to TLS with STARTTLS, which the server must advertise, and forgets the extensions it advertised in plain text

type SMTPError

type SMTPError struct {
	Command string // what was sent, such as MAIL FROM or AUTH PLAIN
	Code    int    // three digit reply code
	Message string // reply text, the lines of a multi line reply joined by line feeds
}

Reply with which an SMTP server ended a command unsuccessfully

func (*SMTPError) Error

func (e *SMTPError) Error() string

Message with the command, the code and the reply text on one line

func (*SMTPError) Is

func (e *SMTPError) Is(target error) bool

Whether the target is ErrAuthFailed and a permanent 5xx reply ended an AUTH exchange

type TLSError

type TLSError struct {
	Host string // server name the certificate was checked against
	Err  error  // failure crypto/tls reported
}

TLS handshake with a mail server that failed for a reason other than a timeout, such as an untrusted certificate or a server that does not speak TLS

func (*TLSError) Error

func (e *TLSError) Error() string

Message naming the server and the failure

func (*TLSError) Unwrap

func (e *TLSError) Unwrap() error

Failure crypto/tls reported

Jump to

Keyboard shortcuts

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