Plain Auth with smtplib imaplib and Python

February 3, 2021

The authenticate and auth function definitions in imaplib.IMAP4_SSL and smtplib.SMTP_SSL are given as

def IMAP4.authenticate(mechanism, authobject)
def SMTP.auth(mechanism, authobject, *, initial_response_ok=True)

However, there seems to be no guidance for implementing authobject for the login type "PLAIN". After a fair amount of reading and guesswork, I've come up with the following implementations for authobject:

imap_auth = lambda ch: f"\0{user}\0{password}".encode()
smtp_auth = lambda: f"\0{user}\0{password}"

Two usage examples are shown below.

import imaplib

imaplib.Debug = 4
imap_auth = lambda ch: f"\0{user}\0{password}".encode()
with imaplib.IMAP4_SSL(host, port=993) as cnx:
    cnx.authenticate("PLAIN", imap_auth)
    typ, data = cnx.list()
import smtplib

smtp_auth = lambda: f"\0{user}\0{password}"
with smtplib.SMTP_SSL(host, port=465) as cnx:
    cnx.set_debuglevel(1)
    cnx.auth("PLAIN", smtp_auth)
    cnx.sendmail(f"{user}@localhost", f"{user}@localhost", "Hello World!")