Sending emails with Go (Golang) and Gmail

Orlando Monteverde
Glottery
Published in
3 min readJul 15, 2019
Gopher Artwork by Ashley McNamara

Requirements

Should I read this post?

Yes, why not? Well, now seriously, this publication assumes that you have used Go (Golang). In this post, we will learn how we can send emails only with the standard Go library and a Gmail account. It’s okay? Go ahead!

It’s coding time!

Configuring Gmail

To run this program you may need to allow access to less secure applications in Gmail, you can do it from this link and activating the switch as shown in the image below.

Gmail

Prepare the workspace

For this project, we will use the go modules, if you do not know what I am talking about, you should probably look for it. But you can work on your GOPATH, ignore the “mod commands” and follow the post.

In the terminal, type the following command, or you can create a directory with a GUI tool, but it is not cool, right?.

mkdir send-email-gmail && cd $_

Inside the new directory, we execute the following command.

go mod init github.com/<username>/send-email-gmail

This creates the go.mod file, but do not worry about that now. With that, we have initialized the module and we can start to coding.

Importing packages

package mainimport (
"fmt"
"net/smtp"
)

Import all the packages that we need in the publication. If you are using an editor or an IDE with automatic import, you may not need to do it.

Set smtp server structure

[...]
// smtpServer data to smtp server
type smtpServer struct {
host string
port string
}
// Address URI to smtp server
func (s *smtpServer) Address() string {
return s.host + ":" + s.port
}

Sending the email

[...]
func main() {
// Sender data.
from := "myuser@gmail.com"
password := "MySecretPassword"
// Receiver email address.
to := []string{
"firstemail@gmail.com",
"secondemail@gmail.com",
}
// smtp server configuration.
smtpServer := smtpServer{host: "smtp.gmail.com", port: "587"}
// Message.
message := []byte("This is a really unimaginative message, I know.")
// Authentication.
auth := smtp.PlainAuth("", from, password, smtpServer.host)
// Sending email.
err := smtp.SendMail(smtpServer.Address(), auth, from, to, message)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Email Sent!")
}

I think the code is really simple and easy to understand. The sender’s data is hardcoded, this is bad practice, but for our example it works. In practice it is better to use a configuration file, environment variables or similar.

The message is just a dummy text, but it can be whatever you want. In combination with templates (see package html/template) it is quite powerful and useful. But it’s a story for another day … and another post.

The full code of this publication is available on GitHub. Thanks for reading, see you next time.

--

--

Orlando Monteverde
Glottery

Web developer, Gopher, Blogger, Open Source enthusiast and professional coffee drinker ☕️.