2

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.

AlexK
  • 2,855
  • 9
  • 16
  • 27
  • 1
    Please post the error as text, not as image (see [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/)). – AlexK Jan 23 '23 at 23:40
  • You might've run into the same issue I had, check the first **NOTE** on my answer here: https://stackoverflow.com/questions/75264107/authenticate-with-exchange-to-access-email-inbox-with-imaplib/75264108#75264108 – GammaGames Jan 30 '23 at 18:37

0 Answers0