Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
golang net/smtp SMTP AUTH LOGIN Auth Handler
// MIT license (c) andelf 2013
import (
"net/smtp"
"errors"
)
type loginAuth struct {
username, password string
}
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, 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("Unkown fromServer")
}
}
return nil, nil
}
// usage:
// auth := LoginAuth("loginname", "password")
// err := smtp.SendMail(smtpServer + ":25", auth, fromAddress, toAddresses, []byte(message))
// or
// client, err := smtp.Dial(smtpServer)
// client.Auth(LoginAuth("loginname", "password"))
@homme
Copy link

homme commented Feb 16, 2015

Very useful, thanks! I've updated the code to submit the username when Start is called, which means one less network exchange.

@alejandrodbm
Copy link

alejandrodbm commented Sep 13, 2018

Extremely grateful to see that this was the answer to all my problems.

Thank you very very much...!

@jagger27
Copy link

jagger27 commented Apr 16, 2019

Such a simple fix. Can't believe the standard library doesn't support LOGIN.

@tmack8080
Copy link

tmack8080 commented Dec 6, 2020

This worked for me using:
Server: smtp-mail.outlook.com
Port: 587
SMTP security: STARTTLS

Thank you for posting.

@andboson
Copy link

andboson commented Feb 20, 2021

thx dude!

@MaoJianwei
Copy link

MaoJianwei commented Jul 7, 2022

this works! many thanks!

@FeranyDev
Copy link

FeranyDev commented Sep 6, 2022

Oh, it's so beautiful.

@AzraelJi
Copy link

AzraelJi commented Nov 17, 2022

666

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment