gomail.v2: gopkg.in/gomail.v2 Index | Examples | Files

package gomail

import "gopkg.in/gomail.v2"

Package gomail provides a simple interface to compose emails and to mail them efficiently.

More info on Github: https://github.com/go-gomail/gomail


m := gomail.NewMessage()
m.SetHeader("From", "alex@example.com")
m.SetHeader("To", "bob@example.com", "cora@example.com")
m.SetAddressHeader("Cc", "dan@example.com", "Dan")
m.SetHeader("Subject", "Hello!")
m.SetBody("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")

d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")

// Send the email to Bob, Cora and Dan.
if err := d.DialAndSend(m); err != nil {

A daemon that listens to a channel and sends all incoming messages.


ch := make(chan *gomail.Message)

go func() {
    d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")

    var s gomail.SendCloser
    var err error
    open := false
    for {
        select {
        case m, ok := <-ch:
            if !ok {
            if !open {
                if s, err = d.Dial(); err != nil {
                open = true
            if err := gomail.Send(s, m); err != nil {
        // Close the connection to the SMTP server if no email was sent in
        // the last 30 seconds.
        case <-time.After(30 * time.Second):
            if open {
                if err := s.Close(); err != nil {
                open = false

// Use the channel in your program to send emails.

// Close the channel to stop the mail daemon.

Efficiently send a customized newsletter to a list of recipients.


// The list of recipients.
var list []struct {
    Name    string
    Address string

d := gomail.NewDialer("smtp.example.com", 587, "user", "123456")
s, err := d.Dial()
if err != nil {

m := gomail.NewMessage()
for _, r := range list {
    m.SetHeader("From", "no-reply@example.com")
    m.SetAddressHeader("To", r.Address, r.Name)
    m.SetHeader("Subject", "Newsletter #1")
    m.SetBody("text/html", fmt.Sprintf("Hello %s!", r.Name))

    if err := gomail.Send(s, m); err != nil {
        log.Printf("Could not send email to %q: %v", r.Address, err)

Send an email using a local SMTP server.


m := gomail.NewMessage()
m.SetHeader("From", "from@example.com")
m.SetHeader("To", "to@example.com")
m.SetHeader("Subject", "Hello!")
m.SetBody("text/plain", "Hello!")

d := gomail.Dialer{Host: "localhost", Port: 587}
if err := d.DialAndSend(m); err != nil {

Send an email using an API or postfix.


m := gomail.NewMessage()
m.SetHeader("From", "from@example.com")
m.SetHeader("To", "to@example.com")
m.SetHeader("Subject", "Hello!")
m.SetBody("text/plain", "Hello!")

s := gomail.SendFunc(func(from string, to []string, msg io.WriterTo) error {
    // Implements you email-sending function, for example by calling
    // an API, or running postfix, etc.
    fmt.Println("From:", from)
    fmt.Println("To:", to)
    return nil

if err := gomail.Send(s, m); err != nil {


From: from@example.com
To: [to@example.com]



Package Files

auth.go doc.go message.go mime.go send.go smtp.go writeto.go

func Send Uses

func Send(s Sender, msg ...*Message) error

Send sends emails using the given Sender.

type Dialer Uses

type Dialer struct {
    // Host represents the host of the SMTP server.
    Host string
    // Port represents the port of the SMTP server.
    Port int
    // Username is the username to use to authenticate to the SMTP server.
    Username string
    // Password is the password to use to authenticate to the SMTP server.
    Password string
    // Auth represents the authentication mechanism used to authenticate to the
    // SMTP server.
    Auth smtp.Auth
    // SSL defines whether an SSL connection is used. It should be false in
    // most cases since the authentication mechanism should use the STARTTLS
    // extension instead.
    SSL bool
    // TSLConfig represents the TLS configuration used for the TLS (when the
    // STARTTLS extension is used) or SSL connection.
    TLSConfig *tls.Config
    // LocalName is the hostname sent to the SMTP server with the HELO command.
    // By default, "localhost" is sent.
    LocalName string

A Dialer is a dialer to an SMTP server.

func NewDialer Uses

func NewDialer(host string, port int, username, password string) *Dialer

NewDialer returns a new SMTP Dialer. The given parameters are used to connect to the SMTP server.

func NewPlainDialer Uses

func NewPlainDialer(host string, port int, username, password string) *Dialer

NewPlainDialer returns a new SMTP Dialer. The given parameters are used to connect to the SMTP server.

Deprecated: Use NewDialer instead.

func (*Dialer) Dial Uses

func (d *Dialer) Dial() (SendCloser, error)

Dial dials and authenticates to an SMTP server. The returned SendCloser should be closed when done using it.

func (*Dialer) DialAndSend Uses

func (d *Dialer) DialAndSend(m ...*Message) error

DialAndSend opens a connection to the SMTP server, sends the given emails and closes the connection.

type Encoding Uses

type Encoding string

Encoding represents a MIME encoding scheme like quoted-printable or base64.

const (
    // QuotedPrintable represents the quoted-printable encoding as defined in
    // RFC 2045.
    QuotedPrintable Encoding = "quoted-printable"
    // Base64 represents the base64 encoding as defined in RFC 2045.
    Base64 Encoding = "base64"
    // Unencoded can be used to avoid encoding the body of an email. The headers
    // will still be encoded using quoted-printable encoding.
    Unencoded Encoding = "8bit"

type FileSetting Uses

type FileSetting func(*file)

A FileSetting can be used as an argument in Message.Attach or Message.Embed.

func Rename Uses

func Rename(name string) FileSetting

Rename is a file setting to set the name of the attachment if the name is different than the filename on disk.


m.Attach("/tmp/0000146.jpg", gomail.Rename("picture.jpg"))

func SetCopyFunc Uses

func SetCopyFunc(f func(io.Writer) error) FileSetting

SetCopyFunc is a file setting to replace the function that runs when the message is sent. It should copy the content of the file to the io.Writer.

The default copy function opens the file with the given filename, and copy its content to the io.Writer.


m.Attach("foo.txt", gomail.SetCopyFunc(func(w io.Writer) error {
    _, err := w.Write([]byte("Content of foo.txt"))
    return err

func SetHeader Uses

func SetHeader(h map[string][]string) FileSetting

SetHeader is a file setting to set the MIME header of the message part that contains the file content.

Mandatory headers are automatically added if they are not set when sending the email.


h := map[string][]string{"Content-ID": {"<foo@bar.mail>"}}
m.Attach("foo.jpg", gomail.SetHeader(h))

type Message Uses

type Message struct {
    // contains filtered or unexported fields

Message represents an email.

func NewMessage Uses

func NewMessage(settings ...MessageSetting) *Message

NewMessage creates a new message. It uses UTF-8 and quoted-printable encoding by default.

func (*Message) AddAlternative Uses

func (m *Message) AddAlternative(contentType, body string, settings ...PartSetting)

AddAlternative adds an alternative part to the message.

It is commonly used to send HTML emails that default to the plain text version for backward compatibility. AddAlternative appends the new part to the end of the message. So the plain text part should be added before the HTML part. See http://en.wikipedia.org/wiki/MIME#Alternative


m.SetBody("text/plain", "Hello!")
m.AddAlternative("text/html", "<p>Hello!</p>")

func (*Message) AddAlternativeWriter Uses

func (m *Message) AddAlternativeWriter(contentType string, f func(io.Writer) error, settings ...PartSetting)

AddAlternativeWriter adds an alternative part to the message. It can be useful with the text/template or html/template packages.


t := template.Must(template.New("example").Parse("Hello {{.}}!"))
m.AddAlternativeWriter("text/plain", func(w io.Writer) error {
    return t.Execute(w, "Bob")

func (*Message) Attach Uses

func (m *Message) Attach(filename string, settings ...FileSetting)

Attach attaches the files to the email.



func (*Message) Embed Uses

func (m *Message) Embed(filename string, settings ...FileSetting)

Embed embeds the images to the email.


m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)

func (*Message) FormatAddress Uses

func (m *Message) FormatAddress(address, name string) string

FormatAddress formats an address and a name as a valid RFC 5322 address.


m.SetHeader("To", m.FormatAddress("bob@example.com", "Bob"), m.FormatAddress("cora@example.com", "Cora"))

func (*Message) FormatDate Uses

func (m *Message) FormatDate(date time.Time) string

FormatDate formats a date as a valid RFC 5322 date.


    "X-Date": {m.FormatDate(time.Now())},

func (*Message) GetHeader Uses

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

GetHeader gets a header field.

func (*Message) Reset Uses

func (m *Message) Reset()

Reset resets the message so it can be reused. The message keeps its previous settings so it is in the same state that after a call to NewMessage.

func (*Message) SetAddressHeader Uses

func (m *Message) SetAddressHeader(field, address, name string)

SetAddressHeader sets an address to the given header field.


m.SetAddressHeader("To", "bob@example.com", "Bob")

func (*Message) SetBody Uses

func (m *Message) SetBody(contentType, body string, settings ...PartSetting)

SetBody sets the body of the message. It replaces any content previously set by SetBody, AddAlternative or AddAlternativeWriter.


m.SetBody("text/plain", "Hello!")

func (*Message) SetDateHeader Uses

func (m *Message) SetDateHeader(field string, date time.Time)

SetDateHeader sets a date to the given header field.


m.SetDateHeader("X-Date", time.Now())

func (*Message) SetHeader Uses

func (m *Message) SetHeader(field string, value ...string)

SetHeader sets a value to the given header field.


m.SetHeader("Subject", "Hello!")

func (*Message) SetHeaders Uses

func (m *Message) SetHeaders(h map[string][]string)

SetHeaders sets the message headers.


    "From":    {m.FormatAddress("alex@example.com", "Alex")},
    "To":      {"bob@example.com", "cora@example.com"},
    "Subject": {"Hello"},

func (*Message) WriteTo Uses

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

WriteTo implements io.WriterTo. It dumps the whole message into w.

type MessageSetting Uses

type MessageSetting func(m *Message)

A MessageSetting can be used as an argument in NewMessage to configure an email.

func SetCharset Uses

func SetCharset(charset string) MessageSetting

SetCharset is a message setting to set the charset of the email.


m = gomail.NewMessage(gomail.SetCharset("ISO-8859-1"))

func SetEncoding Uses

func SetEncoding(enc Encoding) MessageSetting

SetEncoding is a message setting to set the encoding of the email.


m = gomail.NewMessage(gomail.SetEncoding(gomail.Base64))

type PartSetting Uses

type PartSetting func(*part)

A PartSetting can be used as an argument in Message.SetBody, Message.AddAlternative or Message.AddAlternativeWriter to configure the part added to a message.

func SetPartEncoding Uses

func SetPartEncoding(e Encoding) PartSetting

SetPartEncoding sets the encoding of the part added to the message. By default, parts use the same encoding than the message.


m.SetBody("text/plain", "Hello!", gomail.SetPartEncoding(gomail.Unencoded))

type SendCloser Uses

type SendCloser interface {
    Close() error

SendCloser is the interface that groups the Send and Close methods.

type SendFunc Uses

type SendFunc func(from string, to []string, msg io.WriterTo) error

A SendFunc is a function that sends emails to the given addresses.

The SendFunc type is an adapter to allow the use of ordinary functions as email senders. If f is a function with the appropriate signature, SendFunc(f) is a Sender object that calls f.

func (SendFunc) Send Uses

func (f SendFunc) Send(from string, to []string, msg io.WriterTo) error

Send calls f(from, to, msg).

type Sender Uses

type Sender interface {
    Send(from string, to []string, msg io.WriterTo) error

Sender is the interface that wraps the Send method.

Send sends an email to the given addresses.

Package gomail imports 16 packages (graph) and is imported by 486 packages. Updated 2021-01-23. Refresh now. Tools for package owners.