我有一个不使用加密连接的SMTP帐户.我可以使用相同的帐户从C#和Python发送电子邮件没有问题,但使用Go我得到错误: 未加密的连接
这是我正在使用的代码:
package main
import (
"log"
"net/smtp"
)
func main() {
// Set up authentication information.
auth := smtp.PlainAuth(
"",
"user@example.com",
"password",
"mail.example.com",
)
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
err := smtp.SendMail(
"mail.example.com:25",
auth,
"sender@example.org",
[]string{"recipient@example.net"},
[]byte("This is the email body."),
)
if err != nil {
log.Fatal(err)
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*erg 13
这里的问题是smtp.PlainAuth
拒绝通过未加密的连接发送密码.这是为了保护你自己.这样的事情smtp.CRAMMD5Auth
会是一个更好的选择.使用CRAM-MD5时,即使是未加密的连接,也不会泄露您的密码.
如果你想要使用普通的身份验证,你需要制作自己的版本smtp.PlainAuth
.幸运的是,这是一件非常容易的事情.只需从标准库中复制20行左右即可删除:
if !server.TLS {
return "", nil, errors.New("unencrypted connection")
}
Run Code Online (Sandbox Code Playgroud)
http://golang.org/src/pkg/net/smtp/auth.go?s=1820:1882#L41包含代码.
如果您不希望复制代码,可以通过将函数返回的smtp.Auth包装在您自己的类型中来重用标准库实现.通过这种方式,您可以拦截*smtp.ServerInfo
并欺骗实际的Auth机制(来自标准库),即存在加密连接.一定要大力评论,以明确你为什么做你正在做的事情.像这样(未经测试):
type unencryptedAuth struct {
smtp.Auth
}
func (a unencryptedAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
s := *server
s.TLS = true
return a.Auth.Start(&s)
}
auth := unencryptedAuth {
smtp.PlainAuth(
"",
"user@example.com",
"password",
"mail.example.com",
),
}
Run Code Online (Sandbox Code Playgroud)