Initial commit
This commit is contained in:
69
mailer.go
Normal file
69
mailer.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package emailing
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html/template"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
gomail "gopkg.in/mail.v2"
|
||||
)
|
||||
|
||||
type Mailer struct {
|
||||
TemplatesDir string
|
||||
TemplatesConfig *viper.Viper
|
||||
SMTPConfig
|
||||
}
|
||||
|
||||
type SMTPConfig struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
func NewMailer(templates_dir string, tplcfg *viper.Viper, smtpconfig *viper.Viper) (*Mailer, error) {
|
||||
return &Mailer{
|
||||
TemplatesDir: templates_dir,
|
||||
TemplatesConfig: tplcfg,
|
||||
SMTPConfig: SMTPConfig{
|
||||
Host: smtpconfig.GetString("host"),
|
||||
Port: smtpconfig.GetInt("port"),
|
||||
Username: smtpconfig.GetString("username"),
|
||||
Password: smtpconfig.GetString("password"),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *Mailer) Send(emailcfg string, to string, data any) error {
|
||||
cfg := m.TemplatesConfig.Sub(emailcfg)
|
||||
|
||||
files := cfg.GetStringSlice("files")
|
||||
prefixed_files := []string{}
|
||||
for _, f := range files {
|
||||
prefixed_files = append(prefixed_files, m.TemplatesDir+f)
|
||||
}
|
||||
t := template.Must(template.ParseFiles(prefixed_files...))
|
||||
buf := new(bytes.Buffer)
|
||||
if err := t.ExecuteTemplate(buf, "main", data); err != nil {
|
||||
return err
|
||||
}
|
||||
body := buf.String()
|
||||
|
||||
fmt.Println(body)
|
||||
|
||||
message := gomail.NewMessage()
|
||||
|
||||
message.SetHeader("From", m.SMTPConfig.Username)
|
||||
message.SetHeader("To", to)
|
||||
message.SetHeader("Subject", cfg.GetString("subject"))
|
||||
message.SetBody("text/html", body)
|
||||
|
||||
d := gomail.NewDialer(m.SMTPConfig.Host, m.SMTPConfig.Port, m.SMTPConfig.Username, m.SMTPConfig.Password)
|
||||
if err := d.DialAndSend(message); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user