48 lines
1.2 KiB
Go
48 lines
1.2 KiB
Go
package mailer
|
|
|
|
import (
|
|
"RenewCMS/internal/infrastructure/config"
|
|
"errors"
|
|
"net/smtp"
|
|
"strings"
|
|
)
|
|
|
|
type loginAuth struct {
|
|
username string
|
|
password string
|
|
}
|
|
|
|
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
|
if !server.TLS && !isLoopback(server.Name) {
|
|
return "", nil, errors.New("refusing to send credentials over an unencrypted connection")
|
|
}
|
|
return "LOGIN", nil, nil
|
|
}
|
|
|
|
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
|
if !more {
|
|
return nil, nil
|
|
}
|
|
switch strings.ToLower(strings.TrimSpace(string(fromServer))) {
|
|
case "username:":
|
|
return []byte(a.username), nil
|
|
case "password:":
|
|
return []byte(a.password), nil
|
|
}
|
|
return nil, errors.New("unexpected server challenge")
|
|
}
|
|
|
|
func isLoopback(host string) bool {
|
|
return host == "localhost" || host == "127.0.0.1" || host == "::1"
|
|
}
|
|
|
|
func selectAuth(mechanisms string, settings config.SmtpSettings) smtp.Auth {
|
|
advertised := strings.Fields(strings.ToUpper(mechanisms))
|
|
for _, mechanism := range advertised {
|
|
if mechanism == "PLAIN" {
|
|
return smtp.PlainAuth("", settings.Login, settings.Password, settings.Host)
|
|
}
|
|
}
|
|
return &loginAuth{username: settings.Login, password: settings.Password}
|
|
}
|