Python’s smtplib false authentication failures

I ran into a case where Python’s smtplib could not authenticate against some SMTP servers, while others worked just fine (with good valid logins). After some research into the SMTP protocol, a few debug sessions and a pinch of telnet connections to the SMTP server it became apparent that some servers just have quirks which cause authentication to fail when its handled by smtplib.
It seems that smtplib’s login() method will choose its own authentication method, and if it can will use a MD5 Hash, which failed on some servers for some unknown reason.

The solution:

Catch the failure and send manual “AUTH LOGIN” commands with a base64 encoded username and password:

import base64
try:
    # attmept a 'standard' login
    smtp.login( username , password )
except SMTPAuthenticationError, e:
    # if login fails, try again using a manual plain login method
    smtp.docmd("AUTH LOGIN", base64.b64encode( username ))
    smtp.docmd(base64.b64encode( password ), "")

3 Responses to “Python’s smtplib false authentication failures”

Leave a Reply