问题
I am trying to send an email from an Office365 server but I become the following error:
panic: tls: first record does not look like a TLS handshake
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 = "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")
}
回答1:
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)
}
来源:https://stackoverflow.com/questions/54946901/sending-email-from-office365-with-starttls-fails