我正尝试从 Office365 服务器发送电子邮件,但出现以下错误:
panic: tls: first record does not look like a TLS handshake
账户配置如下smtp.office365.com:587 (STARTTLS)。对于身份验证,需要用户名+密码。 我使用的代码与我在网上看到的所有示例非常相似,但我无法让它工作。它在 tls.Dial 处失败。
func Mail() {
mail := Mail{}
mail.senderId = "theemail@example.com"
mail.toIds = []string{"anotheremail@example.com"}
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
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)
}
关于email - 使用 STARTTLS 从 Office365 发送电子邮件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54946901/