TOC

Golang SMTP Login 认证

官方库里面只看到 PlainAuth 和 CramMd5Auth 两种认证方法。

type loginAuth struct {
    username, password string
}

func LoginAuth(username, password string) smtp.Auth {
    return &loginAuth{username, password}
}

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

func (a *loginAuth) Next(fromServer []byte, more bool) (toServer []byte, err error) {
    if more {
        switch strings.ToUpper(string(fromServer)) {
        case "USERNAME:":
            return []byte(a.username), nil
        case "PASSWORD:":
            return []byte(a.password), nil
        default:
            return nil, fmt.Errorf("unknown command %v", fromServer)
        }
    }
    return nil, nil
}