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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器