本文介绍了使用STARTTLS从Office365发送电子邮件失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从Office365服务器发送电子邮件,但出现以下错误:
I am trying to send an email from an Office365 server but I become the following error:
帐户配置为以下smtp.office365.com:587(STARTTLS).为了进行身份验证,需要用户名和密码.我使用的代码与我在网络上看到的所有示例都非常相似,但是我无法使其正常工作.它在tls.Dial失败.
The account configuration is the following smtp.office365.com:587 (STARTTLS). For the authentication an username+password is needed.The code I am using is pretty similar to all the examples I saw in the web but I can't get it to work. It fails at tls.Dial.
func Mail() {
mail := Mail{}
mail.senderId = "[email protected]"
mail.toIds = []string{"[email protected]"}
mail.subject = "This is the email subject"
mail.body = "body"
messageBody := mail.BuildMessage()
smtpServer := SmtpServer{host: "smtp.office365.com", port: "587"}
auth := smtp.PlainAuth("", mail.senderId, `mypassword`, smtpServer.host)
fmt.Println(auth)
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: smtpServer.host,
}
conn, err := tls.Dial("tcp", "smtp.office365.com:587", tlsconfig)
if err != nil {
log.Panic(err)
}
client, err := smtp.NewClient(conn, smtpServer.host)
if err != nil {
log.Panic(err)
}
if err = client.Auth(auth); err != nil {
log.Panic(err)
}
if err = client.Mail(mail.senderId); err != nil {
log.Panic(err)
}
for _, k := range mail.toIds {
if err = client.Rcpt(k); err != nil {
log.Panic(err)
}
}
w, err := client.Data()
if err != nil {
log.Panic(err)
}
_, err = w.Write([]byte(messageBody))
if err != nil {
log.Panic(err)
}
err = w.Close()
if err != nil {
log.Panic(err)
}
client.Quit()
log.Println("Mail sent successfully")
}
推荐答案
您正在尝试在未封装在TLS中的端口上执行tls拨号.如果要使用starttls
You are trying to do a tls dial on a port that isn't encapsulated in TLS.If you want to use starttls
client, err := smtp.Dial("tcp", "smtp.office365.com:587")
if err != nil {
log.Panic(err)
}
err = client.StartTLS(tlsconfig)
if err != nil {
log.Panic(err)
}
这篇关于使用STARTTLS从Office365发送电子邮件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!