Add more general PLAIN/CRAM-MD5 auth support.

This commit is contained in:
Logan Hanks 2015-03-12 14:28:28 -07:00
parent f6ba424325
commit 6d140d7571
1 changed files with 31 additions and 18 deletions

View File

@ -188,26 +188,39 @@ func (n *notifier) sendEmailNotification(to string, a *Alert) error {
} }
defer c.Quit() defer c.Quit()
hasAuth, _ := c.Extension("AUTH") // Authenticate if we and the server are both configured for it.
smtpAuth := os.Getenv("SMTP_AUTH") hasAuth, mechs := c.Extension("AUTH")
if hasAuth && smtpAuth != "" { username := os.Getenv("SMTP_AUTH_USERNAME")
idx := strings.IndexRune(smtpAuth, ':') if hasAuth && username != "" {
if idx < 0 { for _, mech := range strings.Split(mechs, " ") {
return fmt.Errorf("SMTP_AUTH must be in the format username:password") switch mech {
case "CRAM-MD5":
secret := os.Getenv("SMTP_AUTH_SECRET")
if secret == "" {
continue
} }
username := smtpAuth[:idx] if err := c.Auth(smtp.CRAMMD5Auth(username, secret)); err != nil {
password := smtpAuth[idx+1:] return fmt.Errorf("cram-md5 auth failed: %s", err)
}
break
case "PLAIN":
password := os.Getenv("SMTP_AUTH_PASSWORD")
if password == "" {
continue
}
identity := os.Getenv("SMTP_AUTH_IDENTITY")
// PLAIN auth requires TLS to be started first.
host, _, _ := net.SplitHostPort(*smtpSmartHost) host, _, _ := net.SplitHostPort(*smtpSmartHost)
if err := c.StartTLS(&tls.Config{ServerName: host}); err != nil {
if hasTLS, _ := c.Extension("TLS"); hasTLS { return fmt.Errorf("starttls failed: %s", err)
cfg := &tls.Config{ServerName: host}
if err := c.StartTLS(cfg); err != nil {
return err
}
} }
if err := c.Auth(smtp.PlainAuth("", username, password, host)); err != nil { if err := c.Auth(smtp.PlainAuth(identity, username, password, host)); err != nil {
return err return fmt.Errorf("plain auth failed: %s", err)
}
break
}
} }
} }