dsqbkh3630 2019-03-01 14:43
浏览 1040

使用STARTTLS从Office365发送电子邮件失败

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条回答 默认 最新

  • douyou2048 2019-03-01 17:46
    关注

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况