通过未加密的连接发送电子邮件

时间:2012-06-16 18:14:48

标签: go smtp-auth

我有一个不使用加密连接的SMTP帐户。我可以使用相同的帐户从C#和Python发送电子邮件没有问题但是Go我得到错误: 未加密的连接

这是我正在使用的代码:

package main

import (
        "log"
        "net/smtp"
)

func main() {
        // Set up authentication information.
        auth := smtp.PlainAuth(
                "",
                "user@example.com",
                "password",
                "mail.example.com",
        )
        // Connect to the server, authenticate, set the sender and recipient,
        // and send the email all in one step.
        err := smtp.SendMail(
                "mail.example.com:25",
                auth,
                "sender@example.org",
                []string{"recipient@example.net"},
                []byte("This is the email body."),
        )
        if err != nil {
                log.Fatal(err)
        }
}

1 个答案:

答案 0 :(得分:10)

此处的问题是smtp.PlainAuth拒绝通过未加密的连接发送密码。这是为了保护你自己。像smtp.CRAMMD5Auth之类的东西会是更好的选择。使用CRAM-MD5时,即使是未加密的连接,也不会泄露您的密码。

如果您仍想使用普通身份验证,则需要制作自己的smtp.PlainAuth版本。幸运的是,这是一件非常容易的事情。只需从标准库中复制20行左右,然后删除:

if !server.TLS {
    return "", nil, errors.New("unencrypted connection")
}

http://golang.org/src/pkg/net/smtp/auth.go?s=1820:1882#L41包含代码。

如果您不希望复制代码,可以通过将函数返回的smtp.Auth包装在您自己的类型中来重用标准库实现。这样您就可以截取*smtp.ServerInfo并欺骗实际的Auth机制(来自标准库),即存在加密连接。一定要大力评论,以明确你为什么做你正在做的事情。像这样(未经测试):

type unencryptedAuth struct {
    smtp.Auth
}

func (a unencryptedAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
    s := *server
    s.TLS = true
    return a.Auth.Start(&s)
}

auth := unencryptedAuth {
    smtp.PlainAuth(
        "",
        "user@example.com",
        "password",
        "mail.example.com",
    ),
}
相关问题