Support for OAuth2 in poplib/imaplib

Microsoft and Google are (or already have) dropped basic auth (username + password) support in their POP and IMAP servers.

Instead you are now supposed to use OAuth2 which authenticates in a base64 encoded auth token.

This is described in more detail here :

O365 : Authenticate an IMAP, POP or SMTP connection using OAuth | Microsoft Learn

Gmail: OAuth 2.0 Mechanism  |  IMAP for Gmail  |  Google Developers

For e.g. POP all we would need in is something like:

    def oauth(self, token):
        """Send oauth2 authentication token, return response

        return self._shortcmd('AUTH XOAUTH2 %s' % token)

It looks like we need two different implementations unfortunately. Google expects it on a single line, e.g.:

> AUTH XOAUTH2 <token>

While Microsoft expects it on 2 lines, e.g.

< +
> <token>

Is this something we could add tot poplib and imaplib ?


1 Like

I personally would rather drop poplib and imaplib if it’s auth approach is no longer good enough and instead encourage the community to provide projects that provide OAuth2 support. I wouldn’t want us to have to handle the CVEs that would come up because our OAuth2 implementation had a bug in it.


I only see now imaplib can actually already do this via the authenticate function, e.g[1].

imap_conn.authenticate('XOAUTH2', lambda x: auth_string)

But poplib is missing such function.

Microsoft already provides the MSAL library[2] that takes care of all OAuth2 stuff. Google also has google-auth-library-python-oauthlib[3] which presumably does the same. We just need a method to be able to provide the “final” token to poplib.

[1] gmail-oauth2-tools/ at master · google/gmail-oauth2-tools · GitHub
[2] GitHub - AzureAD/microsoft-authentication-library-for-python: Microsoft Authentication Library (MSAL) for Python makes it easy to authenticate to Azure Active Directory. These documented APIs are stable If you have questions but do not have a github account, ask your questions on Stackoverflow with tag "msal" + "python".
[3] github .com/googleapis/google-auth-library-python-oauthlib

As I understand Geert’s suggestion, the two modules would simply receive
methods to allow for sending the OAuth tokens, not the OAuth
implementation itself – which is indeed better handled using the
already existing provide APIs.

It’s unfortunate, though, that MS and GMail are using different
variants of the extension of the protocols for this, so not sure
whether it’s worth adding to the stdlib.