0

I've been using basic auth to log in to my outlook email with imap.

imap = imaplib.IMAP4_SSL("imap-mail.outlook.com")
# authenticate
imap.login(username, password)
status, messages = imap.select("INBOX")

Now that Microsoft moved to oauth2 I'm getting "Login failed" messages even although the credentials are correct. Can anyone share a code example that connects with oauth2?

I found this guide, but it only shows the steps on the account side, not the actual connection in the app. https://docs.emailengine.app/setting-up-oauth2-with-outlook/#:~:text=Navigate%20to%20Configuration-%3EOAuth2%20and,of%20accounts%20your%20application%20supports.

Thanks

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Adi Lerman
  • 61
  • 4
  • 1
    This seems to do the trick: [office-365-imap-authentication-via-oauth2-and-python-msal-library](https://stackoverflow.com/questions/73902642/office-365-imap-authentication-via-oauth2-and-python-msal-library) – Tal Pascovich Oct 30 '22 at 09:28

1 Answers1

2

This is my solution,

  1. follow this guide to create an app with necessary permissions.

https://docs.emailengine.app/setting-up-oauth2-with-outlook/#:%7E:text=Navigate%20to%20Configuration-%3EOAuth2%20and,of%20accounts%20your%20application%20supports

  1. use the following code in your app.

    imap = imaplib.IMAP4_SSL(imap_host, 993)

    imap.debug = 4

    access_token = get_access_token_to_authenticate_imap()

    imap.authenticate("XOAUTH2", lambda x:generate_auth_string( 'useremail', access_token['access_token']))

    imap.select('inbox')

Adi Lerman
  • 61
  • 4