TOC

SMTP 认证

最常见的三种 SMTP 认证方法:

  • PLAIN
  • LOGIN
  • CRAM-MD5

假设用户名是 catroll, 密码是 zV4fzjx7Wjrs7kdK

PLAIN

# base64.b64encode(b'\0catroll\0zV4fzjx7Wjrs7kdK')
C: AUTH PLAIN AGNhdHJvbGwAelY0ZnpqeDdXanJzN2tkSw==
S: 235 Authentication successful

LOGIN

C: AUTH LOGIN
# base64.b64encode(b'Username:')
S: 334 VXNlcm5hbWU6
# base64.b64encode(b'catroll')
C: Y2F0cm9sbA==
# base64.b64encode(b'Password:')
S: 334 UGFzc3dvcmQ6
# base64.b64encode(b'zV4fzjx7Wjrs7kdK')
C: elY0ZnpqeDdXanJzN2tkSw==
S: 235 Authentication successful

也可以 AUTH 时直接提供用户名。

C: AUTH LOGIN Y2F0cm9sbA==
S: 334 UGFzc3dvcmQ6
C: elY0ZnpqeDdXanJzN2tkSw==
S: 235 Authentication successful

CRAM-MD5

C: AUTH CRAM-MD5
# challenge = base64.b64encode(os.urandom(32)) # 示例
S: 334 HSU43fnkj47dskmlSH6dsnjn8ndskjnkjnScdDES=
C: Y2F0cm9sbCA3YzI1Y2Q0ZGYzOGM5YTA1NjM0Y2QzNWRjNTU2YmRlZg==
S: 235 Authentication successful
import hmac, base64
username, password = 'catroll', 'zV4fzjx7Wjrs7kdK'
challenge = 'HSU43fnkj47dskmlSH6dsnjn8ndskjnkjnScdDES='
_h = hmac.new(password.encode(), base64.b64decode(challenge), 'md5')
base64.b64encode((username + ' ' + _h.hexdigest()).encode())