Sending HTML emails using templates in Golang

Dhanush Gopinath
Apr 25, 2016 · 2 min read

In the GeekTrust application we send a lot of emails that are auto-generated at runtime using HTML Templates. In the new application, which we are currently developing in Go, we need the same feature. So this post is a short read about reading a HTML template file and sending email using Go’s html/template and net/smtp packages.

The code is as given below.

In this I encapsulate the smtp request in a struct Request. It contains basic things like To, Subject, Body. This template file has the data placeholders which will be replaced with actual data values by Golang’s html/template package Execute method.

The HTML template file for sending the email

The template data is a struct which has Name & Url as the field values. It is initialised with values and passed to the NewRequest method to create an object of Request.

templateData := struct {
Name string
URL string
}{
Name: “Dhanush”,
URL: “http://geektrust.in",
}

Once the instance of Request is created, then ParseTemplate method is called on it. This method receives a template filename and template data. It parses the template file and executes it with the template data supplied. A bytes.Buffer is passed to the Execute method as io.Writer so that we get back the HTML string with the data replaced. This HTML string is then set as the Email Body.

The SendEmail method sets the MIME encoding as text/html and calls smtp package’s SendMail method to send the email. When the email is sent successfully the SendEmail method returns a true value.


Note:

  1. If you return the Request in ParseTemplate method, instead of the error, then we make the call in one line.
ok,err := NewRequest([]string{“junk@junk.com”}, “Hello Junk!”, “Hello, World!”, “template.html”, templateData).ParseTemplate().SendEmail()

But then any error coming out of ParseTemplate may have to be tracked inside the method.

2. Read the package documentation of html/template to understand how Golang replaces the HTML with actual data.

3. Thanks to Jijesh Mohan and Navaneeth K. N in making the Go code more idiomatic, than it was before :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade