emailing/mailer.go

91 lines
2.1 KiB
Go
Raw Normal View History

2022-10-17 03:03:37 +00:00
package emailing
import (
"bytes"
"fmt"
"html/template"
2025-02-11 06:40:35 +00:00
"net/smtp"
2022-10-17 03:03:37 +00:00
"github.com/spf13/viper"
)
type Mailer struct {
TemplatesDir string
TemplatesConfig *viper.Viper
2025-02-10 05:54:58 +00:00
From string
2022-10-17 03:03:37 +00:00
Host string
Port int
Username string
Password string
}
func NewMailer(templates_dir string, tplcfg *viper.Viper, smtpconfig *viper.Viper) (*Mailer, error) {
2025-02-11 06:40:35 +00:00
var (
from = smtpconfig.GetString("from")
host = smtpconfig.GetString("host")
port = smtpconfig.GetInt("port")
username = smtpconfig.GetString("username")
password = smtpconfig.GetString("password")
)
2022-10-17 03:03:37 +00:00
return &Mailer{
TemplatesDir: templates_dir,
TemplatesConfig: tplcfg,
2025-02-11 06:40:35 +00:00
From: from,
Host: host,
Port: port,
Username: username,
Password: password,
2022-10-17 03:03:37 +00:00
}, nil
}
2025-02-11 06:40:35 +00:00
func (m *Mailer) Send(emailcfg string, to string, data any) error {
2022-10-17 03:03:37 +00:00
cfg := m.TemplatesConfig.Sub(emailcfg)
2025-02-11 06:40:35 +00:00
subject := cfg.GetString("subject")
2022-10-17 03:03:37 +00:00
files := cfg.GetStringSlice("files")
2025-02-11 06:40:35 +00:00
auth := smtp.PlainAuth("", m.Username, m.Password, m.Host)
2025-02-10 05:54:58 +00:00
2025-02-11 06:40:35 +00:00
var body bytes.Buffer
2025-02-10 06:50:24 +00:00
2025-02-11 06:40:35 +00:00
mimeHeaders := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
body.Write([]byte(fmt.Sprintf("Subject: %s \n%s\n\n", subject, mimeHeaders)))
2025-02-11 06:40:35 +00:00
if err := executeTemplate(&body, files, data, m.TemplatesDir); err != nil {
return fmt.Errorf("failed executing email template : %w", err)
2025-02-10 05:54:58 +00:00
}
2025-02-11 06:40:35 +00:00
smtpserver := fmt.Sprintf("%s:%d", m.Host, m.Port)
2025-02-11 06:40:35 +00:00
err := smtp.SendMail(smtpserver, auth, m.From, []string{to}, body.Bytes())
if err != nil {
2025-02-11 06:40:35 +00:00
return fmt.Errorf("isser sending email: %w", err)
2022-10-17 03:03:37 +00:00
}
return nil
}
2025-02-11 06:40:35 +00:00
func executeTemplate(body *bytes.Buffer, files []string, data any, templatesdir string) error {
prefixed_files := []string{}
for _, f := range files {
prefixed_files = append(prefixed_files, templatesdir+f)
}
2025-02-11 06:40:35 +00:00
t := template.New("email").Funcs(
template.FuncMap{
"unescapeHTML": UnescapeHTML,
},
)
t = template.Must(t.ParseFiles(prefixed_files...))
if err := t.ExecuteTemplate(body, "main", data); err != nil {
return fmt.Errorf("failed execute mail template : %w", err)
}
return nil
}
func UnescapeHTML(s string) template.HTML {
return template.HTML(s)
}