Simple Sending

Sending email generally consists of 4 parts:

  1. Connect to the SMTP port
  2. Identify yourself (as the sender)
  3. Identify one or more recipients
  4. Send the message

Note that even though you specify yourself as the send and the recipients, these are not automatically added to the message (depending on the mail server you connect to). The sender/recipients you specify outside of the message are specified as part of the Envelope, which is what the mail servers actually use to determine where to send the message.

The simplest form of send email involves

  • smtp.Dial to create an *smtp.Client
  • (*smtp.Client) Mail to specify the sender. This must be called first.
  • (*smtp.Client) Rcpt to specify a recipient. This can be called multiple times.
  • (*smtp.Client) Data to send the message.
  • (*smtp.Client) Quit to end the connection.

[net/smtp][net/smtp] has the canonical example:

// Connect to the remote SMTP server.
c, err := smtp.Dial("mail.example.com:25")
if err != nil {
    log.Fatal(err)
}

// Set the sender and recipient first
if err := c.Mail("sender@example.org"); err != nil {
    log.Fatal(err)
}
if err := c.Rcpt("recipient@example.net"); err != nil {
    log.Fatal(err)
}

// Send the email body.
wc, err := c.Data()
if err != nil {
    log.Fatal(err)
}
_, err = fmt.Fprintf(wc, "This is the email body")
if err != nil {
    log.Fatal(err)
}
err = wc.Close()
if err != nil {
    log.Fatal(err)
}

// Send the QUIT command and close the connection.
err = c.Quit()
if err != nil {
    log.Fatal(err)
}