Reputation: 1806
I have a following piece of code in which i am trying to send an email using gopkg.in/gomail.v2
. I am perfectly able to send the email when the email template is placed in the root directory of the project like this
./
main.go
template.html
// Info defines
type Info struct {
Age int
Name string
}
func (i Info) sendMail() {
fp := filepath.Join("template.html")
t := template.New(fp)
var err error
t, err = t.ParseFiles(fp)
if err != nil {
log.Println(err)
}
var tpl bytes.Buffer
if err := t.Execute(&tpl, i); err != nil {
log.Println(err)
}
result := tpl.String()
// ... email sending logic
}
func main() {
info := &Info{
Name: "name 1",
Age: 20,
}
info.sendMail()
}
but when i change the template directory to emails/template.html
and change the filepath to
fp := filepath.Join("emails", "template.html")
then I get the error from t.Execute()
template: "emails/template.html" is an incomplete or empty template
I have also tried
fp, _ := filepath.Abs("emails/template.html")
but got error
template: "/mnt/data/go/test/emails/template.html" is an incomplete or empty template
the path mentioned is correct though.
Upvotes: 2
Views: 3422
Reputation: 1806
I changed
if err := t.Execute(&tpl, i); err != nil {
log.Println(err)
}
to
if err := t2.ExecuteTemplate(&tpl, "template.html", i); err != nil {
log.Println(err)
}
and it worked
If I want to use t.Execute(&tpl, i)
instead, then I have to specify the templates name as filename while creating the template
t := template.New("template.html")
Upvotes: 4