go发送邮件提示“unencrypted connection”的解决方法

    在go\src\net\smtp\auth.go文件中注释掉含有“unencrypted connection”的部分

func (a *plainAuth) Start(server *ServerInfo) (string, []byte, error) {
    // Must have TLS, or else localhost server.
    // Note: If TLS is not true, then we can't trust ANYTHING in ServerInfo.
    // In particular, it doesn't matter if the server advertises PLAIN auth.
    // That might just be the attacker saying
    // "it's ok, you can trust me with your password."
    if !server.TLS && !isLocalhost(server.Name) {
        //return "", nil, errors.New("unencrypted connection")
    }
    if server.Name != a.host {
        return "", nil, errors.New("wrong host name")
    }
    resp := []byte(a.identity + "\x00" + a.username + "\x00" + a.password)
    return "PLAIN", resp, nil
}

    举例如下:

// sample project main.go
package main

import (
    "encoding/base64"
    "fmt"
    "log"
    "net/mail"
    "net/smtp"
)

func main() {

    b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")

    host := "mail.xxx.com"
    username := "xxx@xxx.com"
    password := "xxxxxx"

    title := "这是邮件标题"
    from := mail.Address{"发送人名称", "xxx@xxx.com"}
    to := mail.Address{"接收人名称", "xxx@xxx.com"}

    header := make(map[string]string)
    header["From"] = from.String()
    header["To"] = to.String()
    header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(title)))
    header["MIME-Version"] = "1.0"
    header["Content-Type"] = "text/html; charset=UTF-8"
    header["Content-Transfer-Encoding"] = "base64"

    message := ""
    for k, v := range header {
        message += fmt.Sprintf("%s: %s\r\n", k, v)
    }

    body := "这是一封测试邮件!"
    message += "\r\n" + b64.EncodeToString([]byte(body))

    auth := smtp.PlainAuth(
        "",
        username,
        password,
        host,
    )

    err := smtp.SendMail(
        host+":25",
        auth,
        username,
        []string{to.Address},
        []byte(message),
    )

    if err != nil {
        log.Println(err)
        return
    }

    fmt.Println("OK")
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

princewwj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值