搜索出来的使用go 发用邮件的例子并不能成功发送,所以搜到了下面这个用来解决这个问题
504 5.7.4 Unrecognized authentication type
package services
import (
"fmt"
"net/smtp"
"strings"
)
const (
EmailTo = "xxxx@163.com" //发送给谁
EmailFrom = "xxxx@163.com" //谁发的
EmailPass = "xxxxxxx" //密码
EmailHost = "smtp.163.com" //一般是25端口
EmailPort = "25" //一般是25端口
)
type loginAuth struct {
username, password string
}
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
//需要使用Login作为参数
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", nil, nil
}
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
command := string(fromServer)
command = strings.TrimSpace(command)
command = strings.TrimSuffix(command, ":")
command = strings.ToLower(command)
if more {
if command == "username" {
return []byte(fmt.Sprintf("%s", a.username)), nil
} else if command == "password" {
return []byte(fmt.Sprintf("%s", a.password)), nil
} else {
// We've already sent everything.
return nil, fmt.Errorf("unexpected server challenge: %s", command)
}
}
return nil, nil
}
func SendEmail(subject, body string) error {
send_to := strings.Split(EmailTo, ";")
content_type := "Content-Type: text/plain; charset=UTF-8"
msg := []byte("To: All \r\nFrom: " + EmailFrom + " >\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
auth := LoginAuth(EmailFrom, EmailPass)
err := smtp.SendMail(EmailHost+":"+EmailPort, auth, EmailFrom, send_to, msg)
return err
}
需要自己实现smtp.Auth接口 然后Start()方法中添加"Login"参数。
注意:发送的邮箱必须是开启了smtp的,不然会发送不成功。
PS: 觉得不错的请点个赞吧!! (ง •̀_•́)ง