Cannot sign in to office365 account using IMAP and fetch emails

Sayad Ahmed 0 Reputation points
2023-11-20T10:35:11.9066667+00:00

Hi,

We can read emails using IMAP. Let me show an example.

from exchangelib import Credentials, Account
email_address = "your-email@example.com"
password = "your-password"
credentials = Credentials(email_address, password)
account = Account(email_address, credentials=credentials, autodiscover=True)
for item in account.inbox.all().order_by('-datetime_received')[:5]:
     print(item.subject, item.datetime_received)

It does not work for office365 email.

There is also another piece of code.

# IMAP server settings
IMAP_SERVER = "outlook.office365.com"
USERNAME ="******@email.com"
PASSWORD = "password"
# Connect to the IMAP server
imap = imaplib.IMAP4(IMAP_SERVER, port=OUTLOOK_IMAP_PORT)
imap.login(USERNAME, PASSWORD)

But this one also does not work.

  1. Error: {error_proto}b'-ERR Logon failure: unknown user name or bad password.' (I used the password where 2FA is enabled.)
  2. {error}b'LOGIN failed.' (This time, I used third-party app password)

I can read email from my personal Outlook account using the above piece of code but cannot read from office365 mail.

Is the IMAP disabled completely by the office365?
Or I can enable it from somewhere in the admin site and use the above code to read emails from the server?

Exchange Online
Exchange Online
A Microsoft email and calendaring hosted service.
6,188 questions
Microsoft 365 and Office | Install, redeem, activate | For business | Windows
Exchange | Exchange Server | Management
{count} votes

1 answer

Sort by: Most helpful
  1. Vasil Michev 119.8K Reputation points MVP Volunteer Moderator
    2023-11-20T16:49:53.2866667+00:00

    No, IMAP is not disabled, however basic authentication (i.e. using username/password) for login is. To access an O365 mailbox via IMAP, your client must support modern authentication as detailed here: https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth

    Thunderbird should support this.

    2 people found this answer helpful.
    0 comments No comments

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.