Documentation
¶
Overview ¶
Package gomail provides a simple interface to compose emails and to mail them efficiently.
More info on Github: https://github.com/go-mail/mail
Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321. It also implements the following extensions:
8BITMIME RFC 1652 AUTH RFC 2554 STARTTLS RFC 3207
Additional extensions may be handled by clients.
The smtp package is frozen and is not accepting new features. Some external packages provide more functionality. See:
https://godoc.org/?q=smtp
Example ¶
m := mail.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>!") m.Attach("/home/Alex/lolcat.jpg") d := mail.NewDialer("smtp.example.com", 587, "user", "123456") d.StartTLSPolicy = mail.MandatoryStartTLS // Send the email to Bob, Cora and Dan. if err := d.DialAndSend(m); err != nil { panic(err) }
Output:
Example (Daemon) ¶
A daemon that listens to a channel and sends all incoming messages.
ch := make(chan *mail.Message) go func() { d := mail.NewDialer("smtp.example.com", 587, "user", "123456") d.StartTLSPolicy = mail.MandatoryStartTLS var s mail.SendCloser var err error open := false for { select { case m, ok := <-ch: if !ok { return } if !open { if s, err = d.Dial(); err != nil { panic(err) } open = true } if err := mail.Send(s, m); err != nil { log.Print(err) } // 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 { panic(err) } open = false } } } }() // Use the channel in your program to send emails. // Close the channel to stop the mail daemon. close(ch)
Output:
Example (Newsletter) ¶
Efficiently send a customized newsletter to a list of recipients.
// The list of recipients. var list []struct { Name string Address string } d := mail.NewDialer("smtp.example.com", 587, "user", "123456") d.StartTLSPolicy = mail.MandatoryStartTLS s, err := d.Dial() if err != nil { panic(err) } m := mail.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 := mail.Send(s, m); err != nil { log.Printf("Could not send email to %q: %v", r.Address, err) } m.Reset() }
Output:
Example (NoAuth) ¶
Send an email using a local SMTP server.
m := mail.NewMessage() m.SetHeader("From", "from@example.com") m.SetHeader("To", "to@example.com") m.SetHeader("Subject", "Hello!") m.SetBody("text/plain", "Hello!") d := mail.Dialer{Host: "localhost", Port: 587} if err := d.DialAndSend(m); err != nil { panic(err) }
Output:
Example (NoSMTP) ¶
Send an email using an API or postfix.
m := mail.NewMessage() m.SetHeader("From", "from@example.com") m.SetHeader("To", "to@example.com") m.SetHeader("Subject", "Hello!") m.SetBody("text/plain", "Hello!") s := mail.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 := mail.Send(s, m); err != nil { panic(err) }
Output: From: from@example.com To: [to@example.com]
Index ¶
- Variables
- func Send(s Sender, msg ...*Message) error
- func SendMail(addr string, a Auth, from string, to []string, msg []byte) error
- type Auth
- type Client
- func (c *Client) Auth(a Auth) error
- func (c *Client) Close() error
- func (c *Client) Data() (io.WriteCloser, error)
- func (c *Client) Extension(ext string) (bool, string)
- func (c *Client) Hello(localName string) error
- func (c *Client) Mail(from string) error
- func (c *Client) Noop() error
- func (c *Client) Quit() error
- func (c *Client) Rcpt(to string) error
- func (c *Client) Reset() error
- func (c *Client) StartTLS(config *tls.Config) error
- func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)
- func (c *Client) Verify(addr string) error
- type Dialer
- type Encoding
- type FileSetting
- type Message
- func (m *Message) AddAlternative(contentType, body string, settings ...PartSetting)
- func (m *Message) AddAlternativeWriter(contentType string, f func(io.Writer) error, settings ...PartSetting)
- func (m *Message) Attach(filename string, settings ...FileSetting)
- func (m *Message) AttachReader(name string, r io.Reader, settings ...FileSetting)
- func (m *Message) Embed(filename string, settings ...FileSetting)
- func (m *Message) EmbedReader(name string, r io.Reader, settings ...FileSetting)
- func (m *Message) FormatAddress(address, name string) string
- func (m *Message) FormatDate(date time.Time) string
- func (m *Message) GetHeader(field string) []string
- func (m *Message) Reset()
- func (m *Message) SetAddressHeader(field, address, name string)
- func (m *Message) SetBody(contentType, body string, settings ...PartSetting)
- func (m *Message) SetBodyWriter(contentType string, f func(io.Writer) error, settings ...PartSetting)
- func (m *Message) SetBoundary(boundary string)
- func (m *Message) SetDateHeader(field string, date time.Time)
- func (m *Message) SetHeader(field string, value ...string)
- func (m *Message) SetHeaders(h map[string][]string)
- func (m *Message) WriteTo(w io.Writer) (int64, error)
- type MessageSetting
- type PartSetting
- type SendCloser
- type SendError
- type SendFunc
- type Sender
- type ServerInfo
- type StartTLSPolicy
- type StartTLSUnsupportedError
Examples ¶
- Package
- Package (Daemon)
- Package (Newsletter)
- Package (NoAuth)
- Package (NoSMTP)
- Message.AddAlternative
- Message.AddAlternativeWriter
- Message.Attach
- Message.Embed
- Message.FormatAddress
- Message.FormatDate
- Message.SetAddressHeader
- Message.SetBody
- Message.SetBodyWriter
- Message.SetDateHeader
- Message.SetHeader
- Message.SetHeaders
- Rename
- SetCharset
- SetCopyFunc
- SetEncoding
- SetHeader
- SetPartEncoding
Constants ¶
This section is empty.
Variables ¶
var NetDialTimeout = net.DialTimeout
NetDialTimeout specifies the DialTimeout function to establish a connection to the SMTP server. This can be used to override dialing in the case that a proxy or other special behavior is needed.
Functions ¶
func SendMail ¶
SendMail connects to the server at addr, switches to TLS if possible, authenticates with the optional mechanism a if possible, and then sends an email from address from, to addresses to, with message msg. The addr must include a port, as in "mail.example.com:smtp".
The addresses in the to parameter are the SMTP RCPT addresses.
The msg parameter should be an RFC 822-style email with headers first, a blank line, and then the message body. The lines of msg should be CRLF terminated. The msg headers should usually include fields such as "From", "To", "Subject", and "Cc". Sending "Bcc" messages is accomplished by including an email address in the to parameter but not including it in the msg headers.
The SendMail function and the net/smtp package are low-level mechanisms and provide no support for DKIM signing, MIME attachments (see the mime/multipart package), or other mail functionality. Higher-level packages exist outside of the standard library.
Types ¶
type Auth ¶
type Auth interface { // Start begins an authentication with a server. // It returns the name of the authentication protocol // and optionally data to include in the initial AUTH message // sent to the server. // If it returns a non-nil error, the SMTP client aborts // the authentication attempt and closes the connection. Start(server *ServerInfo) (proto string, toServer []byte, err error) // Next continues the authentication. The server has just sent // the fromServer data. If more is true, the server expects a // response, which Next should return as toServer; otherwise // Next should return toServer == nil. // If Next returns a non-nil error, the SMTP client aborts // the authentication attempt and closes the connection. Next(fromServer []byte, more bool) (toServer []byte, err error) }
Auth is implemented by an SMTP authentication mechanism.
func CRAMMD5Auth ¶
CRAMMD5Auth returns an Auth that implements the CRAM-MD5 authentication mechanism as defined in RFC 2195. The returned Auth uses the given username and secret to authenticate to the server using the challenge-response mechanism.
func PlainAuth ¶
PlainAuth returns an Auth that implements the PLAIN authentication mechanism as defined in RFC 4616. The returned Auth uses the given username and password to authenticate to host and act as identity. Usually identity should be the empty string, to act as username.
PlainAuth will only send the credentials if the connection is using TLS or is connected to localhost. Otherwise authentication will fail with an error, without sending the credentials.
type Client ¶
type Client struct { // Text is the textproto.Conn used by the Client. It is exported to allow for // clients to add extensions. Text *textproto.Conn // contains filtered or unexported fields }
A Client represents a client connection to an SMTP server.
func Dial ¶
Dial returns a new Client connected to an SMTP server at addr. The addr must include a port, as in "mail.example.com:smtp".
func NewClient ¶
NewClient returns a new Client using an existing connection and host as a server name to be used when authenticating.
func (*Client) Auth ¶
Auth authenticates a client using the provided authentication mechanism. A failed authentication closes the connection. Only servers that advertise the AUTH extension support this function.
func (*Client) Data ¶
func (c *Client) Data() (io.WriteCloser, error)
Data issues a DATA command to the server and returns a writer that can be used to write the mail headers and body. The caller should close the writer before calling any more methods on c. A call to Data must be preceded by one or more calls to Client.Rcpt.
func (*Client) Extension ¶
Extension reports whether an extension is support by the server. The extension name is case-insensitive. If the extension is supported, Extension also returns a string that contains any parameters the server specifies for the extension.
func (*Client) Hello ¶
Hello sends a HELO or EHLO to the server as the given host name. Calling this method is only necessary if the client needs control over the host name used. The client will introduce itself as "localhost" automatically otherwise. If Hello is called, it must be called before any of the other methods.
func (*Client) Mail ¶
Mail issues a MAIL command to the server using the provided email address. If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME parameter. If the server supports the SMTPUTF8 extension, Mail adds the SMTPUTF8 parameter. This initiates a mail transaction and is followed by one or more Client.Rcpt calls.
func (*Client) Noop ¶
Noop sends the NOOP command to the server. It does nothing but check that the connection to the server is okay.
func (*Client) Rcpt ¶
Rcpt issues a RCPT command to the server using the provided email address. A call to Rcpt must be preceded by a call to Client.Mail and may be followed by a Client.Data call or another Rcpt call.
func (*Client) Reset ¶
Reset sends the RSET command to the server, aborting the current mail transaction.
func (*Client) StartTLS ¶
StartTLS sends the STARTTLS command and encrypts all further communication. Only servers that advertise the STARTTLS extension support this function.
func (*Client) TLSConnectionState ¶
func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)
TLSConnectionState returns the client's TLS connection state. The return values are their zero values if Client.StartTLS did not succeed.
type Dialer ¶
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 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 // TLSConfig represents the TLS configuration used for the TLS (when the // STARTTLS extension is used) or SSL connection. TLSConfig *tls.Config // StartTLSPolicy represents the TLS security level required to // communicate with the SMTP server. // // This defaults to OpportunisticStartTLS for backwards compatibility, // but we recommend MandatoryStartTLS for all modern SMTP servers. // // This option has no effect if SSL is set to true. StartTLSPolicy StartTLSPolicy // LocalName is the hostname sent to the SMTP server with the HELO command. // By default, "localhost" is sent. LocalName string // Timeout to use for read/write operations. Defaults to 10 seconds, can // be set to 0 to disable timeouts. Timeout time.Duration // Whether we should retry mailing if the connection returned an error, // defaults to true. RetryFailure bool }
A Dialer is a dialer to an SMTP server.
func NewDialer ¶
NewDialer returns a new SMTP Dialer. The given parameters are used to connect to the SMTP server.
func NewPlainDialer
deprecated
func (*Dialer) Dial ¶
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 ¶
DialAndSend opens a connection to the SMTP server, sends the given emails and closes the connection.
type Encoding ¶
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 ¶
type FileSetting func(*file)
A FileSetting can be used as an argument in Message.Attach or Message.Embed.
func Rename ¶
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.
Example ¶
m.Attach("/tmp/0000146.jpg", mail.Rename("picture.jpg"))
Output:
func SetCopyFunc ¶
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.
Example ¶
m.Attach("foo.txt", mail.SetCopyFunc(func(w io.Writer) error { _, err := w.Write([]byte("Content of foo.txt")) return err }))
Output:
func SetHeader ¶
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.
Example ¶
h := map[string][]string{"Content-ID": {"<foo@bar.mail>"}} m.Attach("foo.jpg", mail.SetHeader(h))
Output:
type Message ¶
type Message struct {
// contains filtered or unexported fields
}
Message represents an email.
func NewMessage ¶
func NewMessage(settings ...MessageSetting) *Message
NewMessage creates a new message. It uses UTF-8 and quoted-printable encoding by default.
func (*Message) AddAlternative ¶
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
Example ¶
m.SetBody("text/plain", "Hello!") m.AddAlternative("text/html", "<p>Hello!</p>")
Output:
func (*Message) AddAlternativeWriter ¶
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.
Example ¶
t := template.Must(template.New("example").Parse("Hello {{.}}!")) m.AddAlternativeWriter("text/plain", func(w io.Writer) error { return t.Execute(w, "Bob") })
Output:
func (*Message) Attach ¶
func (m *Message) Attach(filename string, settings ...FileSetting)
Attach attaches the files to the email.
Example ¶
m.Attach("/tmp/image.jpg")
Output:
func (*Message) AttachReader ¶
func (m *Message) AttachReader(name string, r io.Reader, settings ...FileSetting)
AttachReader attaches a file using an io.Reader
func (*Message) Embed ¶
func (m *Message) Embed(filename string, settings ...FileSetting)
Embed embeds the images to the email.
Example ¶
m.Embed("/tmp/image.jpg") m.SetBody("text/html", `<img src="cid:image.jpg" alt="My image" />`)
Output:
func (*Message) EmbedReader ¶
func (m *Message) EmbedReader(name string, r io.Reader, settings ...FileSetting)
EmbedReader embeds the images to the email.
func (*Message) FormatAddress ¶
FormatAddress formats an address and a name as a valid RFC 5322 address.
Example ¶
m.SetHeader("To", m.FormatAddress("bob@example.com", "Bob"), m.FormatAddress("cora@example.com", "Cora"))
Output:
func (*Message) FormatDate ¶
FormatDate formats a date as a valid RFC 5322 date.
Example ¶
m.SetHeaders(map[string][]string{ "X-Date": {m.FormatDate(time.Now())}, })
Output:
func (*Message) Reset ¶
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 ¶
SetAddressHeader sets an address to the given header field.
Example ¶
m.SetAddressHeader("To", "bob@example.com", "Bob")
Output:
func (*Message) SetBody ¶
func (m *Message) SetBody(contentType, body string, settings ...PartSetting)
SetBody sets the body of the message. It replaces any content previously set by SetBody, SetBodyWriter, AddAlternative or AddAlternativeWriter.
Example ¶
m.SetBody("text/plain", "Hello!")
Output:
func (*Message) SetBodyWriter ¶
func (m *Message) SetBodyWriter(contentType string, f func(io.Writer) error, settings ...PartSetting)
SetBodyWriter sets the body of the message. It can be useful with the text/template or html/template packages.
Example ¶
t := template.Must(template.New("example").Parse("Hello {{.}}!")) m.SetBodyWriter("text/plain", func(w io.Writer) error { return t.Execute(w, "Bob") })
Output:
func (*Message) SetBoundary ¶
SetBoundary sets a custom multipart boundary.
func (*Message) SetDateHeader ¶
SetDateHeader sets a date to the given header field.
Example ¶
m.SetDateHeader("X-Date", time.Now())
Output:
func (*Message) SetHeader ¶
SetHeader sets a value to the given header field.
Example ¶
m.SetHeader("Subject", "Hello!")
Output:
func (*Message) SetHeaders ¶
SetHeaders sets the message headers.
Example ¶
m.SetHeaders(map[string][]string{ "From": {m.FormatAddress("alex@example.com", "Alex")}, "To": {"bob@example.com", "cora@example.com"}, "Subject": {"Hello"}, })
Output:
type MessageSetting ¶
type MessageSetting func(m *Message)
A MessageSetting can be used as an argument in NewMessage to configure an email.
func SetCharset ¶
func SetCharset(charset string) MessageSetting
SetCharset is a message setting to set the charset of the email.
Example ¶
m = mail.NewMessage(mail.SetCharset("ISO-8859-1"))
Output:
func SetEncoding ¶
func SetEncoding(enc Encoding) MessageSetting
SetEncoding is a message setting to set the encoding of the email.
Example ¶
m = mail.NewMessage(mail.SetEncoding(mail.Base64))
Output:
type PartSetting ¶
type PartSetting func(*part)
A PartSetting can be used as an argument in Message.SetBody, Message.SetBodyWriter, Message.AddAlternative or Message.AddAlternativeWriter to configure the part added to a message.
func SetPartEncoding ¶
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.
Example ¶
m.SetBody("text/plain", "Hello!", mail.SetPartEncoding(mail.Unencoded))
Output:
type SendCloser ¶
SendCloser is the interface that groups the Send and Close methods.
type SendError ¶
type SendError struct { // Index specifies the index of the Message within a batch. Index uint Cause error }
A SendError represents the failure to transmit a Message, detailing the cause of the failure and index of the Message within a batch.
type SendFunc ¶
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.
type Sender ¶
Sender is the interface that wraps the Send method.
Send sends an email to the given addresses.
type ServerInfo ¶
type ServerInfo struct { Name string // SMTP server name TLS bool // using TLS, with valid certificate for Name Auth []string // advertised authentication mechanisms }
ServerInfo records information about an SMTP server.
type StartTLSPolicy ¶
type StartTLSPolicy int
StartTLSPolicy constants are valid values for Dialer.StartTLSPolicy.
const ( // OpportunisticStartTLS means that SMTP transactions are encrypted if // STARTTLS is supported by the SMTP server. Otherwise, messages are // sent in the clear. This is the default setting. OpportunisticStartTLS StartTLSPolicy = iota // MandatoryStartTLS means that SMTP transactions must be encrypted. // SMTP transactions are aborted unless STARTTLS is supported by the // SMTP server. MandatoryStartTLS // NoStartTLS means encryption is disabled and messages are sent in the // clear. NoStartTLS = -1 )
func (*StartTLSPolicy) String ¶
func (policy *StartTLSPolicy) String() string
type StartTLSUnsupportedError ¶
type StartTLSUnsupportedError struct {
Policy StartTLSPolicy
}
StartTLSUnsupportedError is returned by Dial when connecting to an SMTP server that does not support STARTTLS.
func (StartTLSUnsupportedError) Error ¶
func (e StartTLSUnsupportedError) Error() string