// Package notifier provides functionality. package notifier import ( "crypto/tls" "errors" "fmt" "net/mail" "github.com/microcosm-cc/bluemonday" "gopkg.in/gomail.v2" "rocketgit.ru/rsmon/worker/app/models" ) // SendEmail provides functionality. func SendEmail(to, subject, body string) error { p := bluemonday.StripTagsPolicy() cred, err := firstSMTPCredential() if err != nil { return err } fromAddr := &mail.Address{Name: cred.fromName, Address: cred.fromAddress} from := fromAddr.String() m := gomail.NewMessage() m.SetHeader("From", from) m.SetHeader("To", to) m.SetHeader("Subject", subject) // m.SetBody("text/html", body) m.AddAlternative("text/plain", p.Sanitize(body)) m.AddAlternative("text/html", body) d := gomail.NewDialer( cred.server, cred.port, cred.login, cred.password, ) if cred.insecureSkipVerify { d.TLSConfig = &tls.Config{InsecureSkipVerify: true} } return d.DialAndSend(m) } type smtpCredential struct { server string port int login string password string fromName string fromAddress string insecureSkipVerify bool } func firstSMTPCredential() (*smtpCredential, error) { creds, err := models.EnabledCredentialsByKind(models.CredentialKindSMTP) if err != nil { return nil, err } if len(creds) == 0 { return nil, errors.New("smtp credential is not configured") } c := &creds[0] password, err := c.GetSecret() if err != nil { return nil, fmt.Errorf("smtp credential secret: %w", err) } out := &smtpCredential{password: password, insecureSkipVerify: c.InsecureSkipVerify} if c.Server != nil { out.server = *c.Server } if c.Port != nil { out.port = *c.Port } if c.Login != nil { out.login = *c.Login } if c.FromName != nil { out.fromName = *c.FromName } if c.FromAddr != nil { out.fromAddress = *c.FromAddr } return out, nil }