Connecting to Exchange with Golang
Asked Answered
D

1

7

How do I connect with Exchange server with Go? I have tried:

func main() {

to := "[email protected]"
from := "[email protected]"
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)
}
}

This code returns:

504 5.7.4 Unrecognized authentication type

I'm porting over Python/Django code, and it has a setting where I mark have to declare:

EMAIL_USE_TLS = True

Perhaps something similar in Go?

Delano answered 17/2, 2017 at 19:16 Comment(1)
Take a look at this example: gist.github.com/chrisgillis/10888032Jasun
B
8

Office does not support AUTH PLAIN after August 2017. Ref. However, it does support AUTH LOGIN. AUTH LOGIN does not have a native Golang implementation but here is a working one:

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
}

Replace this auth implementation with the stmp.PlainAuth from Golang lib and it should work accordingly.

Bonsai answered 16/12, 2019 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.