2019-12-06 10:59:00 +01:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-01-15 13:40:35 +01:00
|
|
|
type MailSender struct {
|
|
|
|
BodyTemplate string
|
2019-12-06 10:59:00 +01:00
|
|
|
|
2020-01-15 13:40:35 +01:00
|
|
|
mailTpl *template.Template
|
|
|
|
config *config.ConfigT
|
|
|
|
}
|
2019-12-06 10:59:00 +01:00
|
|
|
|
2020-01-15 13:40:35 +01:00
|
|
|
func NewMailSender(config *config.ConfigT, mailBody string) *MailSender {
|
|
|
|
ms := new(MailSender)
|
2019-12-06 10:59:00 +01:00
|
|
|
|
2020-01-15 13:40:35 +01:00
|
|
|
ms.config = config
|
|
|
|
ms.mailTpl = template.Must(template.New("subscription_mail").Parse(mailBody))
|
2019-12-06 10:59:00 +01:00
|
|
|
|
2020-01-15 13:40:35 +01:00
|
|
|
return ms
|
2019-12-06 10:59:00 +01:00
|
|
|
}
|
|
|
|
|
2020-01-15 13:40:35 +01:00
|
|
|
func (ms *MailSender) SendSubscriptionMail(rcv Subscriber) error {
|
2019-12-06 10:59:00 +01:00
|
|
|
var body bytes.Buffer
|
|
|
|
|
|
|
|
m := gomail.NewMessage()
|
2020-01-15 13:40:35 +01:00
|
|
|
m.SetHeader("Subject", ms.config.Smtp.Subject)
|
|
|
|
m.SetHeader("From", ms.config.Smtp.From)
|
2019-12-06 10:59:00 +01:00
|
|
|
m.SetHeader("To", rcv.To())
|
2020-01-15 13:40:35 +01:00
|
|
|
m.SetHeader("Bcc", ms.config.Smtp.Bcc)
|
2019-12-06 10:59:00 +01:00
|
|
|
|
2020-01-15 13:40:35 +01:00
|
|
|
err := ms.mailTpl.Execute(&body, rcv)
|
2019-12-06 10:59:00 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
m.SetBody("text/plain", body.String())
|
|
|
|
|
|
|
|
dialer := gomail.NewDialer(
|
2020-01-15 13:40:35 +01:00
|
|
|
ms.config.Smtp.Host,
|
|
|
|
ms.config.Smtp.Port,
|
|
|
|
ms.config.Smtp.Username,
|
|
|
|
ms.config.Smtp.Password,
|
2019-12-06 10:59:00 +01:00
|
|
|
)
|
|
|
|
dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true}
|
|
|
|
|
|
|
|
if err := dialer.DialAndSend(m); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
|
|
|
}
|