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.



Name string

URL string

}{

Name: “Dhanush”,

URL: “

} templateData := struct {Name stringURL 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.