Sending Email with Go

To obtain your SMTP credentials you can create a free outbound account with CloudMailin.

Sending with SMTP

Sending email in Go (GoLang) is simple with the inbuilt net/smtp package. Go will automatically attempt to negotiate a TLS connection using STARTTLS when using SendMail.

All we need to do is create smtp.PlainAuth to perform authentication. Like CloudMailin Go will only perform plain auth once the TLS connection is established (docs).

package main

import (
  "log"
  "net/smtp"
)

func main() {
  // hostname is used by PlainAuth to validate the TLS certificate.
  hostname := "host from account"
  auth := smtp.PlainAuth("", "username from account", "password fromo account", hostname)

  msg := `To: to@example.net
From: from@example.com
Subject: Testing from GoLang

This is the message content!
Thanks
`
  err := smtp.SendMail(hostname+":587", auth, "from@example.com", []string{"to@example.net"},
    []byte(msg))
  if err != nil {
    log.Fatal(err)
  }
}

Creating a Mime Message

In the example above we manually constructed the email content. An email message is structured by a number of headers followed by an empty line and then the content. Multipart mime messages can be used to include multiple parts such plain and html versions of the content.

It's possible to construct messages in Go in a number of ways. Either manually, using templates or by using additional third-party libaries. If you need help with emails in go feel free to contact us.

Summary

We should now have received a message in our inbox. Using CloudMailin we can also track the status of each of our emails and see the delivery details. Any tags you've added as a x-cloudmta-tags header can be used to filter the email messages and search.

If you need any SMTP credentials you can create an account for free and get your SMTP credentials on the outbound account page.

Make sure you changed the from address to match your verified domain and set a recipient

Outbound Dashboard Showing Message

The SMTP transaction will reply with the message-id of the message to use for bounce tracking if required.

250 Thanks! Queued as: f78b876d-dd97-4e10-9a61-067f98044cc7

Of course if there are any questions feel free to contact us and we'll do our best to help you get setup sending email.