go-mail

repository·main·Indexed 23 days ago

https://github.com/wneessen/go-mail

A comprehensive, idiomatic Go library for composing, encoding, signing, and sending emails via SMTP or local sendmail. It functions as a programmatic Mail User Agent (MUA) with support for DKIM and S/MIME signing, various SMTP authentication mechanisms (including XOAUTH2 and NTLM), and integration with html/template and text/template for message bodies.

Tokens
14.3K
Snippets
13
Records
84
Agent score
80%

What's inside go-mail

  1. Overview of go-mail

    main
    go-mail is a modern, feature-rich Go library designed for composing and sending emails. It functions like a programmatic Mail User Agent (MUA), providing a single package that handles mail composition, encoding, signing (DKIM, S/MIME), and SMTP delivery. It is built primarily on the Go Standard Library to maintain a small dependency footprint and follows Go best practices, including the use of context for timeout and cancellation handling.
  2. Compatibility and Go version support

    main
    go-mail aligns its support with the official Go release policy. It will always support the set of Go versions that the Go team actively maintains. This typically means roughly one year of guaranteed compatibility for any given Go version. Users are encouraged to stay current with supported Go versions to receive security updates and performance improvements.
  3. Key features of go-mail

    main

    go-mail provides several advanced email capabilities:

    • SMTP & Security: Implicit SSL/TLS, explicit STARTTLS with various policies, and support for multiple SMTP authentication mechanisms (CRAM-MD5, LOGIN, PLAIN, NTLM, SCRAM-SHA-1/256, XOAUTH2).
    • Composition: Support for attachments and inline embeds (from io.Reader, fs.FS, embed.FS, or the file system), and integration with html/template and text/template for message bodies.
    • Signing & Validation: DKIM signature support, S/MIME signing (RSA and ECDSA), and RFC5322 compliant mail address validation.
    • Extensibility: Middleware support to alter messages and custom dial-context functions for advanced connection control (e.g., proxying).
    • Data Handling: EML import/export, support for requesting MDNs (RFC 8098) and DSNs (RFC 1891), and concurrency-safe reuse of SMTP connections.
  4. MIME encoding, charset, and content type definitions

    main

    The mail package provides several type wrappers to ensure type safety when working with email metadata such as character sets, MIME types, and encodings. These types implement the fmt.Stringer interface, allowing them to be used directly in formatted output.

    Core Types

    • Charset: Represents character encodings (e.g., UTF-8).
    • ContentType: Represents MIME types for content (e.g., text/html).
    • Encoding: Represents the transfer encoding used for message parts (e.g., base64).
    • MIMEVersion: Represents the MIME version (e.g., 1.0).
    • MIMEType: Represents specific MIME subtypes (e.g., mixed).
  5. What is Middleware and how to use it

    main

    A Middleware is an interface used to modify or handle an email message before it is processed. Multiple middlewares can be applied to a Msg and are executed in FIFO (First-In, First-Out) order.

    To implement a middleware, you must satisfy the Middleware interface:

    type Middleware interface {
    	Handle(*Msg) *Msg
    	Type() MiddlewareType
    }
    • Handle(*Msg) *Msg: Performs the processing logic and must return the modified Msg.
    • Type() MiddlewareType: Returns a unique MiddlewareType to ensure the same middleware is not applied more than once.

    You can attach middleware to a message during creation using WithMiddleware(middleware).

  6. PGP Encryption and Signing types

    main

    The Msg struct supports PGP (Pretty Good Privacy) through the PGPType abstraction. This is used to determine how the message should be treated regarding encryption or digital signatures.

    Available PGPType values:

    • NoPGP: The default value; no PGP processing is applied.
    • PGPEncrypt: Indicates the message should be PGP encrypted (works with go-mail-middleware).
    • PGPSignature: Indicates the message should be PGP signed (works with go-mail-middleware).

    You can set this using WithPGPType(pgptype PGPType) during message creation or SetPGPType(pgptype PGPType) on an existing message.

  7. How the msgWriter handles message construction

    main

    The msgWriter (internal struct) is responsible for the complex I/O operations required to transform a Msg object into a valid MIME-compliant email stream. It manages:

    1. Header Writing: Automatically handles folding long headers to respect MaxHeaderLength and ensures headers like From, To, Cc, and Reply-To are correctly formatted.
    2. Multipart Management: Tracks the nesting depth of multipart structures (e.g., mixed, related, alternative) and manages the creation and closing of multipart.Writer instances.
    3. Encoding: Applies appropriate content transfer encodings such as EncodingB64 (Base64) or EncodingQP (Quoted-Printable) to message parts and attachments.
    4. File Handling: Automatically determines MIME types for attachments/embeds based on file extensions and handles filename sanitization to prevent issues with MIME headers or file systems.
  8. Manage 'CC' (Carbon Copy) recipients

    main

    Manage secondary recipients using these methods:

    • Set multiple recipients: Use Cc(rcpts ...string) to set the 'CC' field. This overwrites existing 'CC' addresses. Returns an error if any address is invalid.
    • Add a single recipient: Use AddCc(rcpt string) to append to the existing list without overwriting.
    • Add using mail.Address objects: Use CcMailAddress(rcpts ...*mail.Address) to set recipients using pre-validated mail.Address instances, or AddCcMailAddress(rcpt *mail.Address) to append one.
    • Add with name and email: Use AddCcFormat(name, addr string) to append a formatted recipient.
    • Parse from string: Use CcFromString(rcpts string) to set 'CC' addresses from a comma-separated string (overwrites existing).
    • Ignore invalid addresses: Use CcIgnoreInvalid(rcpts ...string) to add recipients without erroring on invalid ones.
  9. Manage 'BCC' (Blind Carbon Copy) recipients

    main

    Manage hidden recipients using these methods:

    • Set multiple recipients: Use Bcc(rcpts ...string) to set the 'BCC' field (overwrites existing).
    • Add a single recipient: Use AddBcc(rcpt string) to append to the existing list.
    • Add using mail.Address objects: Use BccMailAddress(rcpts ...*mail.Address) to set, or AddBccMailAddress(rcpt *mail.Address) to append.
    • Add with name and email: Use AddBccFormat(name, addr string) to append a formatted recipient.
    • Parse from string: Use BccFromString(rcpts string) to set 'BCC' addresses from a comma-separated string (overwrites existing).
    • Ignore invalid addresses: Use BccIgnoreInvalid(rcpts ...string) to add recipients without erroring on invalid ones.
  10. Connect to the SMTP server

    main

    Use the following methods to establish a connection:

    • DialWithContext(ctxDial context.Context): Establishes a connection to the server using the provided context. This creates an active, cancelable connection on the Client.
    • DialToSMTPClientWithContext(ctxDial context.Context): Returns a raw *smtp.Client instead of attaching it to the Client instance. This is useful if you want to manage the underlying SMTP client manually.
  11. Attach rendered templates as file attachments

    main

    You can generate files on the fly by executing a template and attaching the result as a file attachment to the message.

    Available methods on *Msg:

    • AttachTextTemplate(name string, tpl *tt.Template, data any, opts ...FileOption): Attaches a rendered text template as a file named name.
    • AttachNamedTextTemplate(fileName string, tpl *tt.Template, tplName string, data any, opts ...FileOption): Attaches a specific named text template as a file named fileName.
    • AttachHTMLTemplate(name string, tpl *ht.Template, data any, opts ...FileOption): Attaches a rendered HTML template as a file named name.
    • AttachNamedHTMLTemplate(fileName string, tpl *ht.Template, tplName string, data any, opts ...FileOption): Attaches a specific named HTML template as a file named fileName.