Add support for SMTP 'LOGIN' auth

This commit is contained in:
Kailash Nadh 2020-04-01 19:56:40 +05:30
parent 71803ab1af
commit 9dcd716f91
2 changed files with 36 additions and 3 deletions

View File

@ -79,7 +79,7 @@ max_idle = 10
host = "my.smtp.server" host = "my.smtp.server"
port = "25" port = "25"
# cram | plain | empty for no auth # "cram", "plain", or "login". Empty string for no auth.
auth_protocol = "cram" auth_protocol = "cram"
username = "xxxxx" username = "xxxxx"
password = "" password = ""

View File

@ -1,6 +1,7 @@
package messenger package messenger
import ( import (
"errors"
"fmt" "fmt"
"math/rand" "math/rand"
"net/smtp" "net/smtp"
@ -11,6 +12,12 @@ import (
const emName = "email" const emName = "email"
// loginAuth is used for enabling SMTP "LOGIN" auth.
type loginAuth struct {
username string
password string
}
// Server represents an SMTP server's credentials. // Server represents an SMTP server's credentials.
type Server struct { type Server struct {
Name string Name string
@ -42,10 +49,16 @@ func NewEmailer(srv ...Server) (Messenger, error) {
for _, server := range srv { for _, server := range srv {
s := server s := server
var auth smtp.Auth var auth smtp.Auth
if s.AuthProtocol == "cram" { switch s.AuthProtocol {
case "cram":
auth = smtp.CRAMMD5Auth(s.Username, s.Password) auth = smtp.CRAMMD5Auth(s.Username, s.Password)
} else if s.AuthProtocol == "plain" { case "plain":
auth = smtp.PlainAuth("", s.Username, s.Password, s.Host) auth = smtp.PlainAuth("", s.Username, s.Password, s.Host)
case "login":
auth = &loginAuth{username: s.Username, password: s.Password}
case "":
default:
return nil, fmt.Errorf("unknown SMTP auth typer '%s'", s.AuthProtocol)
} }
pool, err := email.NewPool(fmt.Sprintf("%s:%d", s.Host, s.Port), s.MaxConns, auth) pool, err := email.NewPool(fmt.Sprintf("%s:%d", s.Host, s.Port), s.MaxConns, auth)
@ -115,3 +128,23 @@ func (e *emailer) Push(fromAddr string, toAddr []string, subject string, m []byt
func (e *emailer) Flush() error { func (e *emailer) Flush() error {
return nil return nil
} }
// https://gist.github.com/andelf/5118732
// Adds support for SMTP LOGIN auth.
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, nil
}
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(a.username), nil
case "Password:":
return []byte(a.password), nil
default:
return nil, errors.New("unkown SMTP fromServer")
}
}
return nil, nil
}