I am trying to connect to the email outlook using OAUTH 2.0. But it get this error : imaplib.error: AUTHENTICATE failed.
Here is my code :
from imap_tools import Any, MailBox
import msal
class CustomBaseException(Exception):def __init__(self, **kwargs: Any):super().__init__()self.kwargs = kwargs
def __repr__(self) -> str:return f"{self.__class__.__name__}: {repr(self.kwargs)}"
def __str__(self) -> str:return repr(self)
class AccessTokenNotRetrieved(CustomBaseException):pass
def init_mailbox_with_xoauth2() -> MailBox:
app = msal.ConfidentialClientApplication(client_id=client_id,authority='https://login.microsoftonline.com/tenant_id',client_credential=client_secret)
scope = ['https://outlook.office365.com/.default']access_token_dict_key = "access_token"token = app.acquire_token_silent(scope, account=None)
if not token:token = app.acquire_token_for_client(scopes=scope)
if access_token_dict_key in token:access_token = token[access_token_dict_key]print(access_token)mailbox = MailBox('outlook.office365.com').xoauth2('trolyao_******@outlook.com', access_token, initial_folder='INBOX')
return mailbox
else:raise AccessTokenNotRetrieved(message="Unable to retrieve access token from AAD.",error=token.get("error"),error_description=token.get("error_description"),correlation_id=token.get("correlation_id") # You may need this when reporting a bug)
print(init_mailbox_with_xoauth2())