jetz
4/11/2016 - 9:31 AM

golang net/smtp SMTP AUTH LOGIN Auth Handler

golang net/smtp SMTP AUTH LOGIN Auth Handler

/////////////////////////////////////////////////////////////////////
// MIT license (c) jetz 2016
//
// 具体参考:http://being23.github.io/2015/09/17/使用golang发送邮件
//
// 报错504 5.7.4 Unrecognized authentication type。这是由于我司的邮
// 件服务支持LOGIN认证方式,不支持go提供的认证方式 (CRAMMD5和PLAIN)。
/////////////////////////////////////////////////////////////////////
package main

import (
	"errors"
	"net/smtp"
)

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