From b065d6e5e8be8104611511cde47f374efe365922 Mon Sep 17 00:00:00 2001 From: thinker007 Date: Fri, 28 Jul 2023 19:48:57 +0800 Subject: [PATCH] Update email.go --- common/email.go | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/common/email.go b/common/email.go index 74f4cccd..8657fb9f 100644 --- a/common/email.go +++ b/common/email.go @@ -7,18 +7,49 @@ import ( "net/smtp" "strings" ) +type loginAuth struct { + username, password string +} + +func LoginAuth(username, password string) smtp.Auth { + return &loginAuth{username, password} +} + + +func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) { + return "LOGIN", []byte(a.username), 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("Unknown from server") + } + } + return nil, nil +} func SendEmail(subject string, receiver string, content string) error { if SMTPFrom == "" { // for compatibility SMTPFrom = SMTPAccount } + tlsconfig := &tls.Config { + ServerName: host, +} encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", base64.StdEncoding.EncodeToString([]byte(subject))) mail := []byte(fmt.Sprintf("To: %s\r\n"+ "From: %s<%s>\r\n"+ "Subject: %s\r\n"+ "Content-Type: text/html; charset=UTF-8\r\n\r\n%s\r\n", receiver, SystemName, SMTPFrom, encodedSubject, content)) - auth := smtp.PlainAuth("", SMTPAccount, SMTPToken, SMTPServer) + + //auth := smtp.PlainAuth("", SMTPAccount, SMTPToken, SMTPServer) addr := fmt.Sprintf("%s:%d", SMTPServer, SMTPPort) to := strings.Split(receiver, ";") var err error @@ -35,6 +66,14 @@ func SendEmail(subject string, receiver string, content string) error { if err != nil { return err } + if err = client.StartTLS(tlsconfig); err != nil { + return err +} + auth := LoginAuth(SMTPAccount, SMTPToken) + +if err = client.Auth(auth); err != nil { + return err +} defer client.Close() if err = client.Auth(auth); err != nil { return err