To generate and serve HTML email templates in Go applications, you can follow the steps below:
Install the html/template
package by running the following command:
go get -u html/template
Create an HTML email template file with the .html
extension. For example, email_template.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Hello {{.Name}},</h1>
<p>This is an example email template.</p>
</body>
</html>
Create a Go handler to serve the HTML template as an email. For example:
package main
import (
"html/template"
"net/http"
)
type EmailData struct {
Name string
}
func emailHandler(w http.ResponseWriter, r *http.Request) {
// Load the email template file
tpl, err := template.ParseFiles("email_template.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Create data to be passed to the template
data := EmailData{Name: "John"}
// Generate the email template using the data
err = tpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func main() {
http.HandleFunc("/email", emailHandler)
http.ListenAndServe(":8080", nil)
}
Run your Go application:
go run main.go
Access the generated email template by visiting http://localhost:8080/email
. You should see the email rendered with the provided data.
You can modify the HTML template and pass different data according to your needs. Additionally, you can use other libraries like gomail
or net/smtp
to actually send the generated email using an email service.