I'm trying to access office365 through IMAP4 using IMAPLIB.I used to use the default authentication method with login and password and it used to work very well, since Microsoft has shifted its authentication method to OAuth2.0, I have been having problems to authenticate through IMAPLIB using OAuth2.
The following error happens: Image ERROR
Even though I am able to generate the access_token, I'm not able to authenticate it.
class IMAPLIB_Authenticator():
"""
"""
def _get_acess_token(self) -> str:
client_id = 'my_secret_id'
tenant_id = 'my_tenant_id'
client_secret = 'my_client_secret'
scope = ['https://outlook.office.com/.default']
authority = 'https://login.microsoftonline.com/' + tenant_id
app = ConfidentialClientApplication(client_id,
authority=authority,
client_credential = client_secret)
return app.acquire_token_for_client(scopes=scope)
def login(self, username):
def _generate_auth_str(u: str, t: str) -> str:
return f"user={u}\x01auth=Bearer {t}\x01\x01"
self.mail = imaplib.IMAP4_SSL("outlook.office365.com", 993)
self.mail.debug = 10
self.mail.authenticate("XOAUTH2", lambda x: _generate_auth_str(
username, self._get_acess_token()['access_token']))
I've tried everything, I've tried to change the scope, I've tried to cryptograph the string to base64, and nothing works.
I'm expecting to authenticate successfully.