【问题标题】:Sending email from Office365 with STARTTLS fails使用 STARTTLS 从 Office365 发送电子邮件失败
【发布时间】:2019-07-23 14:53:23
【问题描述】:

我正在尝试从 Office365 服务器发送电子邮件,但出现以下错误:

恐慌:tls:第一条记录看起来不像 TLS 握手

账户配置如下 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")

}

【问题讨论】:

    标签: email go starttls


    【解决方案1】:

    您正在尝试在未封装在 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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 2014-05-20
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多