Imap authentication of a registered app fails with acquired access token.

Simon Nigg 0 Reputation points
2024-06-28T09:05:46.6833333+00:00

I would like to access office365 emails from within a python script.

I am able to acquire an access_token but the subsequent authentication call (using imaplib) fails with (imaplib debug output):

51:24.89 > b'LIBE1 AUTHENTICATE XOAUTH2'

51:24.91 < b'+ '

51:24.91 write literal size 2084

51:25.81 < b'LIBE1 NO AUTHENTICATE failed.'

51:25.81 NO response: b'AUTHENTICATE failed.'

I am testing with the following script:

import imaplib

import msal

app = msal.ConfidentialClientApplication(

client_id='CLIENT_ID',

authority="https://login.microsoftonline.com/TENANT_ID",

client_credential="SECRET_KEY_VALUE"
```)

result = app.acquire_token_for_client(scopes=['https://outlook.office365.com/.default'])

def generate_auth_string(user, token):

  return 'user=%s\1auth=Bearer %s\1\1' % (user, token)

# IMAP time!

mailserver = 'outlook.office365.com'

imapport = 993

imap = imaplib.IMAP4_SSL(mailserver, imapport)

imap.debug = 4

imap.authenticate('XOAUTH2', lambda _: generate_auth_string('USER_EMAIL_ADDRESS', result['access_token']))

print(result)

What could be the cause? Is there perhaps some additional step that needs to be taken in the app registration web app? How can I get more informative logs of what exactly is going wrong with the authentication? I have been able to reproduce the same failure using openssl and telnet on the command line by issuing the individual imap protocol commands but this provides no additional information beyond "NO AUTHENTICATE failed".

Outlook
Outlook
A family of Microsoft email and calendar products.
4,058 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
4,006 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.