使用Golang连接到Exchange

时间:2017-02-17 19:16:14

标签: go smtp exchange-server

如何使用Go连接Exchange服务器?我试过了:

func main() {

to := "first.last@acme.com"
from := "me@acme.com"
password := "myKey"
subject := "Subject Here"
msg := "Message here"

emailTemplate := `To: %s
Subject: %s

%s
`
body := fmt.Sprintf(emailTemplate, to, subject, msg)
auth := smtp.PlainAuth("", from, password, "smtp.office365.com")
err := smtp.SendMail(
    "smtp.office365.com:587",
    auth,
    from,
    []string{to},
    []byte(body),
)
if err != nil {
    log.Fatal(err)
}
}

此代码返回:

504 5.7.4 Unrecognized authentication type

我正在移植Python / Django代码,它有一个我必须声明的设置:

EMAIL_USE_TLS = True

Go中可能有类似内容吗?

1 个答案:

答案 0 :(得分:0)

2017年8月之后,Office不支持AUTH PLAIN。Ref。但是,它确实支持AUTH LOGIN。 AUTH LOGIN没有本地Golang实现,但这是一个有效的实现:

type loginAuth struct {
    username, password string
}

// LoginAuth is used for smtp login auth
func LoginAuth(username, password string) smtp.Auth {
    return &loginAuth{username, password}
}

func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
    return "LOGIN", []byte(a.username), nil
}

func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
    if more {
        switch string(fromServer) {
        case "Username:":
            return []byte(a.username), nil
        case "Password:":
            return []byte(a.password), nil
        default:
            return nil, errors.New("Unknown from server")
        }
    }
    return nil, nil
}

用Golang库中的stmp.PlainAuth替换此身份验证实现,它应该可以正常工作。