Creating email templates
To start with, we’ll keep the content of the welcome email really simple, with a short message to let the user know that their registration was successful and to confirm their ID number. Similar to this:
Hi, Thanks for signing up for a Greenlight account. We're excited to have you on board! For future reference, your user ID number is 123. Thanks, The Greenlight Team
There are several different approaches we could take to define and manage the content for this email, but a convenient and flexible way is to use Go’s templating functionality from the html/template package.
If you’re following along, begin by creating a new internal/mailer/templates folder in your project directory and then add a user_welcome.tmpl file. Like so:
$ mkdir -p internal/mailer/templates $ touch internal/mailer/templates/user_welcome.tmpl
Inside this file, we’re going to define three named templates to use as part of our welcome email:
- A
"subject"template containing the subject line for the email. - A
"plainBody"template containing the plain-text variant of the email message body. - A
"htmlBody"template containing the HTML variant of the email message body.
Go ahead and update the internal/mailer/templates/user_welcome.tmpl file to include the content for these templates:
{{define "subject"}}Welcome to Greenlight!{{end}}
{{define "plainBody"}}
Hi,
Thanks for signing up for a Greenlight account. We're excited to have you on board!
For future reference, your user ID number is {{.ID}}.
Thanks,
The Greenlight Team
{{end}}
{{define "htmlBody"}}
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Hi,</p>
<p>Thanks for signing up for a Greenlight account. We're excited to have you on board!</p>
<p>For future reference, your user ID number is {{.ID}}.</p>
<p>Thanks,</p>
<p>The Greenlight Team</p>
</body>
</html>
{{end}}
If you’ve read Let’s Go, this template syntax and structure should look very familiar to you, and we won’t dwell on the details again here. But basically:
- We’ve defined the three named templates using the
{{define "..."}}...{{end}}tags. - You can render dynamic data in these templates via the
.character (referred to as dot). In the next chapter we’ll pass aUserstruct to the templates as dynamic data, which means that we can then render the user’s ID using the tag{{.ID}}in the templates.