Sending email from Office365 with STARTTLS fails

孤人 提交于 2021-02-17 06:20:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!