oef/mail/mail.go

68 lines
1.2 KiB
Go
Raw Normal View History

package mail
import (
"bytes"
"crypto/tls"
"text/template"
"git.andreafazzi.eu/andrea/oef/config"
"gopkg.in/gomail.v2"
)
type Subscriber interface {
NameForMail() string
Username() string
Password() string
To() string
Cc() string
}
type MailSender struct {
BodyTemplate string
mailTpl *template.Template
config *config.ConfigT
}
func NewMailSender(config *config.ConfigT, mailBody string) *MailSender {
ms := new(MailSender)
ms.config = config
ms.mailTpl = template.Must(template.New("subscription_mail").Parse(mailBody))
return ms
}
func (ms *MailSender) SendSubscriptionMail(rcv Subscriber) error {
var body bytes.Buffer
m := gomail.NewMessage()
m.SetHeader("Subject", ms.config.Smtp.Subject)
m.SetHeader("From", ms.config.Smtp.From)
m.SetHeader("To", rcv.To())
m.SetHeader("Cc", rcv.Cc())
m.SetHeader("Bcc", ms.config.Smtp.Bcc)
err := ms.mailTpl.Execute(&body, rcv)
if err != nil {
return err
}
m.SetBody("text/plain", body.String())
dialer := gomail.NewDialer(
ms.config.Smtp.Host,
ms.config.Smtp.Port,
ms.config.Smtp.Username,
ms.config.Smtp.Password,
)
dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true}
if err := dialer.DialAndSend(m); err != nil {
return err
}
return nil
}