udemy-go-web-2/cmd/api/mailer.go

79 lines
1.8 KiB
Go
Raw Normal View History

2024-08-20 20:20:37 +00:00
package main
import (
"bytes"
"embed"
"fmt"
"text/template"
2024-08-20 20:36:16 +00:00
"time"
mail "github.com/xhit/go-simple-mail/v2"
2024-08-20 20:20:37 +00:00
)
//go:embed templates
var emailTemplateFS embed.FS
func (app *application) SendMail(from, to, subject, tmpl string, data interface{}) error {
2024-08-21 07:39:34 +00:00
templateToRender := fmt.Sprintf("templates/%s.html.gohtml", tmpl)
2024-08-20 20:20:37 +00:00
t, err := template.New("email-html").ParseFS(emailTemplateFS, templateToRender)
if err != nil {
app.errorLog.Println(err)
return err
}
var tpl bytes.Buffer
if err = t.ExecuteTemplate(&tpl, "body", data); err != nil {
app.errorLog.Println(err)
return err
}
formattedMessage := tpl.String()
2024-08-21 07:39:34 +00:00
templateToRender = fmt.Sprintf("templates/%s.plain.gohtml", tmpl)
2024-08-20 20:20:37 +00:00
t, err = template.New("email-plain").ParseFS(emailTemplateFS, templateToRender)
if err != nil {
app.errorLog.Println(err)
return err
}
if err = t.ExecuteTemplate(&tpl, "body", data); err != nil {
app.errorLog.Println(err)
return err
}
plainMessage := tpl.String()
app.infoLog.Println(formattedMessage, plainMessage)
2024-08-20 20:36:16 +00:00
// send the mail
server := mail.NewSMTPClient()
server.Host = app.config.smtp.host
server.Port = app.config.smtp.port
// NOTE: not needed for MailHog
// server.Username = app.config.smtp.username
// server.Password = app.config.smtp.password
// server.Encryption = mail.EncryptionTLS
server.KeepAlive = false
server.ConnectTimeout = 10 * time.Second
server.SendTimeout = 10 * time.Second
smtpClient, err := server.Connect()
if err != nil {
return err
}
email := mail.NewMSG()
email.SetFrom(from).AddTo(to).SetSubject(subject)
email.SetBody(mail.TextHTML, formattedMessage)
email.AddAlternative(mail.TextPlain, plainMessage)
err = email.Send(smtpClient)
if err != nil {
app.errorLog.Println(err)
return err
}
app.infoLog.Println("send mail")
2024-08-20 20:20:37 +00:00
return nil
}