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 := "[email protected]"
    password := "xxxxxx"

    title := "这是邮件标题"
    from := mail.Address{"发送人名称", "[email protected]"}
    to := mail.Address{"接收人名称", "[email protected]"}

    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")
}

你可能感兴趣的:(go编程语言实现,go,smtp,unencrypted,connection)