mailer

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: BSD-3-Clause Imports: 30 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

gouef mailer logo

mailer

Composable mailer package for Go with MIME building, transports, failover, and DKIM support.
Build plain-text and HTML e-mails, attach files and inline assets, and send through SMTP, sendmail, or native transport wrappers.

Features · Usage · Security · Compatibility · Contributors

Static Badge Stable Version GitHub Release GitHub Release GoDoc Go Report Card codecov

Go package for composing e-mails.

[!TIP]

Quick start:

message := mailer.New().
  SetFrom("noreply@example.com").
  AddTo("john@example.com").
  SetSubject("Welcome").
  SetTextBody("Hello from Gouef Mailer")

smtpMailer := mailer.NewSMTPMailer("smtp.example.com", 587).
  SetAuth("smtp-user", "smtp-password").
  SetSecurity(mailer.SecurityStartTLS)

if err := smtpMailer.Send(message); err != nil {
  log.Fatal(err)
}

✨ Features

  • Fluent message builder
  • To, Cc, Bcc and Reply-To recipients
  • Plain text and HTML bodies
  • Multipart/alternative output
  • File and in-memory attachments
  • Inline attachments with Content-ID
  • Custom e-mail headers
  • Auto-generated Message-ID
  • List-Unsubscribe helpers (including One-Click)
  • SMTP failover (multiple servers)
  • Fallback mailer chaining
  • Message interceptors
  • DKIM signing (RSA-SHA256)
  • Sendmail transport
  • Native transport wrapper
  • Priority, Return-Path, Read-Receipt, Organization helpers
  • First-class Address type

🚀 Usage

📨 Build a Message
package main

import (
  "fmt"
  "log"

  "github.com/gouef/mailer"
)

func main() {
  message := mailer.New().
    SetFrom("noreply@example.com").
    AddTo("john@example.com").
    AddCc("team@example.com").
    SetReplyTo([]string{"support@example.com"}).
    SetSubject("Welcome").
    SetTextBody("Hello from text version").
    SetHtmlBody("<h1>Hello from HTML version</h1>")

  if _, err := message.AddAttachmentFromPath("./invoice.pdf"); err != nil {
    log.Fatal(err)
  }

  mimeMessage, err := message.ToMIME()
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println(string(mimeMessage))
}
👤 Addresses with Display Names
message := mailer.New()

if _, err := message.SetFromAddress("noreply@example.com", "Billing Bot"); err != nil {
  log.Fatal(err)
}
if _, err := message.AddToAddress("john@example.com", "John Doe"); err != nil {
  log.Fatal(err)
}

from, err := mailer.NewAddress("billing@example.com", "Billing Team")
if err != nil {
  log.Fatal(err)
}
if _, err := message.SetFromMailbox(from); err != nil {
  log.Fatal(err)
}

to := []mailer.Address{}
toJohn, _ := mailer.NewAddress("john@example.com", "John Doe")
toJane, _ := mailer.NewAddress("jane@example.com", "Jane Doe")
to = append(to, toJohn, toJane)

if _, err := message.SetToMailboxes(to); err != nil {
  log.Fatal(err)
}
🖼️ Add Inline Image
if _, err := message.AddEmbeddedFile("./logo.png", "logo-cid"); err != nil {
  log.Fatal(err)
}

message.SetHtmlBody(`<p><img src="cid:logo-cid" alt="Logo" /></p>`)
📤 Send via SMTP
smtpMailer := mailer.NewSMTPMailer("smtp.example.com", 587).
  SetAuth("smtp-user", "smtp-password").
  SetSecurity(mailer.SecurityStartTLS)

if err := smtpMailer.Send(message); err != nil {
  log.Fatal(err)
}

If you use SMTP authentication, prefer SecurityStartTLS on port 587 or SecurityTLS on port 465. SecurityAuto will not send credentials over an unencrypted connection.

📮 Send via Sendmail
sendmail := mailer.NewSendmailMailer("/usr/sbin/sendmail")
if err := sendmail.Send(message); err != nil {
  log.Fatal(err)
}
🧰 Send via Native Transport
nativeMailer, err := mailer.NewNativeMailer()
if err != nil {
  log.Fatal(err)
}

if err := nativeMailer.Send(message); err != nil {
  log.Fatal(err)
}
🔁 SMTP Failover
smtpMailer := mailer.NewSMTPMailer("smtp-primary.example.com", 587).
  AddServer("smtp-backup.example.com", 587).
  SetAuth("smtp-user", "smtp-password").
  SetSecurity(mailer.SecurityStartTLS)

The mailer tries servers in order until sending succeeds.

🛟 Fallback Mailer
primary := mailer.NewSMTPMailer("smtp-primary.example.com", 587)
backup := mailer.NewSMTPMailer("smtp-backup.example.com", 587)

sender := mailer.NewFallbackMailer(primary, backup)
if err := sender.Send(message); err != nil {
  log.Fatal(err)
}
🪝 Interceptor
smtpMailer := mailer.NewSMTPMailer("smtp.example.com", 587).
  Use(func(m *mailer.Message) error {
    m.SetHeader("X-App", "billing")
    return nil
  })

Interceptors run before MIME generation and sending.

✍️ DKIM
pemKey := []byte(`-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----`)

signer, err := mailer.NewDKIMSigner("example.com", "mail", pemKey)
if err != nil {
  log.Fatal(err)
}

smtpMailer := mailer.NewSMTPMailer("smtp.example.com", 587).
  SetDKIMSigner(signer)

sendmail := mailer.NewSendmailMailer("/usr/sbin/sendmail").
  SetDKIMSigner(signer)
🏷️ Additional Message Metadata
message.
  SetPriority(1).
  SetReturnPath("bounce@example.com").
  SetReadReceiptTo("receipt@example.com").
  SetOrganization("Gouef").
  SetMessageID("custom-id@example.com")

For SMTPS on port 465:

smtpMailer := mailer.NewSMTPMailer("smtp.example.com", 465).
  SetAuth("smtp-user", "smtp-password").
  SetSecurity(mailer.SecurityTLS)

If you explicitly need plaintext SMTP AUTH for a trusted local relay, use SecurityNone.

🔐 Security

  • SMTP authentication is blocked on unencrypted connections unless you explicitly use SecurityNone.
  • SecurityAuto will not send credentials over plaintext SMTP.
  • Custom header names are validated before serialization.
  • Invalid header names containing :, CR, or LF are ignored.
  • Header values are normalized to a single line during MIME serialization.
  • Invalid raw address strings are not emitted into address headers.

Notes:

  • SecurityNone is an explicit opt-in for plaintext SMTP and should only be used with trusted local relays or controlled networks.
  • Attachments loaded from disk are read fully into memory.
  • The sendmail and native transports trust the selected local sendmail binary and host environment.

🧩 Compatibility Notes

The API shape follows Mail concepts where practical in Go:

  • SetFrom, AddTo, AddCc, AddBcc, SetSubject
  • SetFromAddress, AddToAddress, AddCcAddress, AddBccAddress, AddReplyToAddress
  • SetFromMailbox, AddToMailbox, AddCcMailbox, AddBccMailbox, AddReplyToMailbox
  • SetFromMailboxes (exactly one sender)
  • SetToMailboxes, SetCcMailboxes, SetBccMailboxes, SetReplyToMailboxes
  • AddToMailboxes, AddCcMailboxes, AddBccMailboxes, AddReplyToMailboxes
  • SetTextBody, SetHtmlBody
  • AddAttachmentFromPath, AddEmbeddedFile
  • AddHeader / SetHeader
  • SetListUnsubscribe, SetListUnsubscribePostOneClick
  • Use interceptor hooks
  • SetDKIMSigner

Custom headers added with AddHeader and SetHeader are validated before serialization. Invalid header names such as names containing :, CR, or LF are ignored.

SMTP transport is available through NewSMTPMailer(...).Send(message).

The package now includes both message composition and SMTP transport.

🛠️ Development

  • Edit go.mod and rename to your package module
  • Uncomment .github/workflows/tests.yml

🤝 Contributing

Read Contributing

Contributors

💬 Community

Discord

Click above to join our community on Discord!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Address

type Address struct {
	Email string
	Name  string
}

func NewAddress

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

func ParseAddressValue

func ParseAddressValue(raw string) (Address, error)

func (Address) MustString

func (a Address) MustString() string

func (Address) String

func (a Address) String() (string, error)

type Attachment

type Attachment struct {
	Name        string
	Data        []byte
	ContentType string
	Inline      bool
	ContentID   string
}

func NewAttachment

func NewAttachment(name string, data []byte) Attachment

func NewInlineAttachment

func NewInlineAttachment(name string, data []byte, contentID string) Attachment

type DKIMSigner

type DKIMSigner struct {
	Domain     string
	Selector   string
	Identity   string
	Headers    []string
	PrivateKey *rsa.PrivateKey
}

func NewDKIMSigner

func NewDKIMSigner(domain string, selector string, privateKeyPEM []byte) (*DKIMSigner, error)

func (*DKIMSigner) Sign

func (s *DKIMSigner) Sign(mime []byte) ([]byte, error)

type FallbackMailer

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

func NewFallbackMailer

func NewFallbackMailer(mailers ...Sender) *FallbackMailer

func (*FallbackMailer) AddMailer

func (m *FallbackMailer) AddMailer(mailer Sender) *FallbackMailer

func (*FallbackMailer) Send

func (m *FallbackMailer) Send(message *Message) error

func (*FallbackMailer) Use

func (m *FallbackMailer) Use(interceptor Interceptor) *FallbackMailer

type Interceptor

type Interceptor func(message *Message) error

type Mailer

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

func NewSMTPMailer

func NewSMTPMailer(host string, port int) *Mailer

func (*Mailer) AddServer

func (m *Mailer) AddServer(host string, port int) *Mailer

func (*Mailer) Send

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

func (*Mailer) SetAuth

func (m *Mailer) SetAuth(username string, password string) *Mailer

func (*Mailer) SetDKIMSigner

func (m *Mailer) SetDKIMSigner(signer *DKIMSigner) *Mailer

func (*Mailer) SetInsecureSkipVerify

func (m *Mailer) SetInsecureSkipVerify(skip bool) *Mailer

func (*Mailer) SetSecurity

func (m *Mailer) SetSecurity(mode SecurityMode) *Mailer

func (*Mailer) SetServers

func (m *Mailer) SetServers(servers []SMTPServer) *Mailer

func (*Mailer) SetTimeout

func (m *Mailer) SetTimeout(timeout time.Duration) *Mailer

func (*Mailer) Use

func (m *Mailer) Use(interceptor Interceptor) *Mailer

type Message

type Message struct {
	From        []string
	To          []string
	Cc          []string
	Bcc         []string
	ReplyTo     []string
	Subject     string
	Body        string
	TextBody    string
	HTMLBody    string
	Headers     map[string][]string
	Attachments []Attachment
}

func New

func New() *Message

func NewMessage

func NewMessage(from *[]string, to *[]string, subject *string, body *string) *Message

func (*Message) AddAttachment

func (m *Message) AddAttachment(name string, data []byte) *Message

func (*Message) AddAttachmentFromPath

func (m *Message) AddAttachmentFromPath(path string) (*Message, error)

func (*Message) AddBcc

func (m *Message) AddBcc(bcc string) *Message

func (*Message) AddBccAddress

func (m *Message) AddBccAddress(address string, name string) (*Message, error)

func (*Message) AddBccMailbox

func (m *Message) AddBccMailbox(mailbox Address) (*Message, error)

func (*Message) AddBccMailboxes

func (m *Message) AddBccMailboxes(mailboxes ...Address) (*Message, error)

func (*Message) AddCc

func (m *Message) AddCc(cc string) *Message

func (*Message) AddCcAddress

func (m *Message) AddCcAddress(address string, name string) (*Message, error)

func (*Message) AddCcMailbox

func (m *Message) AddCcMailbox(mailbox Address) (*Message, error)

func (*Message) AddCcMailboxes

func (m *Message) AddCcMailboxes(mailboxes ...Address) (*Message, error)

func (*Message) AddEmbeddedFile

func (m *Message) AddEmbeddedFile(path string, contentID string) (*Message, error)

func (*Message) AddFrom

func (m *Message) AddFrom(from string) *Message

func (*Message) AddFromAddress

func (m *Message) AddFromAddress(address string, name string) (*Message, error)

func (*Message) AddFromMailbox

func (m *Message) AddFromMailbox(mailbox Address) (*Message, error)

func (*Message) AddHeader

func (m *Message) AddHeader(name string, value string) *Message

func (*Message) AddReplyTo

func (m *Message) AddReplyTo(replyTo string) *Message

func (*Message) AddReplyToAddress

func (m *Message) AddReplyToAddress(address string, name string) (*Message, error)

func (*Message) AddReplyToMailbox

func (m *Message) AddReplyToMailbox(mailbox Address) (*Message, error)

func (*Message) AddReplyToMailboxes

func (m *Message) AddReplyToMailboxes(mailboxes ...Address) (*Message, error)

func (*Message) AddTo

func (m *Message) AddTo(to string) *Message

func (*Message) AddToAddress

func (m *Message) AddToAddress(address string, name string) (*Message, error)

func (*Message) AddToMailbox

func (m *Message) AddToMailbox(mailbox Address) (*Message, error)

func (*Message) AddToMailboxes

func (m *Message) AddToMailboxes(mailboxes ...Address) (*Message, error)

func (*Message) Clone

func (m *Message) Clone() *Message

func (*Message) GetBcc

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

func (*Message) GetBody

func (m *Message) GetBody() string

func (*Message) GetCc

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

func (*Message) GetFrom

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

func (*Message) GetHeader

func (m *Message) GetHeader(name string) []string

func (*Message) GetReplyTo

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

func (*Message) GetSubject

func (m *Message) GetSubject() string

func (*Message) GetTo

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

func (*Message) Recipients

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

func (*Message) SetBcc

func (m *Message) SetBcc(bcc []string) *Message

func (*Message) SetBccMailboxes

func (m *Message) SetBccMailboxes(mailboxes []Address) (*Message, error)

func (*Message) SetBody

func (m *Message) SetBody(body string) *Message

func (*Message) SetCc

func (m *Message) SetCc(cc []string) *Message

func (*Message) SetCcMailboxes

func (m *Message) SetCcMailboxes(mailboxes []Address) (*Message, error)

func (*Message) SetDate

func (m *Message) SetDate(date time.Time) *Message

func (*Message) SetFrom

func (m *Message) SetFrom(from string) *Message

func (*Message) SetFromAddress

func (m *Message) SetFromAddress(address string, name string) (*Message, error)

func (*Message) SetFromMailbox

func (m *Message) SetFromMailbox(mailbox Address) (*Message, error)

func (*Message) SetFromMailboxes

func (m *Message) SetFromMailboxes(mailboxes []Address) (*Message, error)

func (*Message) SetHeader

func (m *Message) SetHeader(name string, value string) *Message

func (*Message) SetHtmlBody

func (m *Message) SetHtmlBody(body string) *Message

func (*Message) SetListUnsubscribe

func (m *Message) SetListUnsubscribe(values ...string) *Message

func (*Message) SetListUnsubscribePostOneClick

func (m *Message) SetListUnsubscribePostOneClick() *Message

func (*Message) SetMessageID

func (m *Message) SetMessageID(messageID string) *Message

func (*Message) SetOrganization

func (m *Message) SetOrganization(organization string) *Message

func (*Message) SetPriority

func (m *Message) SetPriority(priority int) *Message

func (*Message) SetReadReceiptTo

func (m *Message) SetReadReceiptTo(address string) *Message

func (*Message) SetReplyTo

func (m *Message) SetReplyTo(replyTo []string) *Message

func (*Message) SetReplyToMailboxes

func (m *Message) SetReplyToMailboxes(mailboxes []Address) (*Message, error)

func (*Message) SetReturnPath

func (m *Message) SetReturnPath(address string) *Message

func (*Message) SetSubject

func (m *Message) SetSubject(subject string) *Message

func (*Message) SetTextBody

func (m *Message) SetTextBody(body string) *Message

func (*Message) SetTo

func (m *Message) SetTo(to []string) *Message

func (*Message) SetToMailboxes

func (m *Message) SetToMailboxes(mailboxes []Address) (*Message, error)

func (*Message) ToMIME

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

type NativeMailer

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

func NewNativeMailer

func NewNativeMailer() (*NativeMailer, error)

func NewNativeMailerWithPath

func NewNativeMailerWithPath(path string) *NativeMailer

func (*NativeMailer) Send

func (m *NativeMailer) Send(message *Message) error

func (*NativeMailer) SetDKIMSigner

func (m *NativeMailer) SetDKIMSigner(signer *DKIMSigner) *NativeMailer

func (*NativeMailer) Use

func (m *NativeMailer) Use(interceptor Interceptor) *NativeMailer

type SMTPServer

type SMTPServer struct {
	Host string
	Port int
}

type SecurityMode

type SecurityMode string
const (
	SecurityAuto     SecurityMode = "auto"
	SecurityNone     SecurityMode = "none"
	SecurityStartTLS SecurityMode = "starttls"
	SecurityTLS      SecurityMode = "tls"
)

type Sender

type Sender interface {
	Send(message *Message) error
}

type SendmailMailer

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

func NewSendmailMailer

func NewSendmailMailer(path string, args ...string) *SendmailMailer

func (*SendmailMailer) Send

func (m *SendmailMailer) Send(message *Message) error

func (*SendmailMailer) SetDKIMSigner

func (m *SendmailMailer) SetDKIMSigner(signer *DKIMSigner) *SendmailMailer

func (*SendmailMailer) Use

func (m *SendmailMailer) Use(interceptor Interceptor) *SendmailMailer

Jump to

Keyboard shortcuts

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