pythonsmtpoffice365imaptwo-factor-authentication

connect to Outlook server using imap has error b'LOGIN failed.'


I have a Microsoft account, that is an enterprise account, and I want to use IMAP in Python to connect to the Outlook server, port 993. I got this error after running ('b'LOGIN failed.''). I also used app passwords or disabled all 2FA, still get this error.  Please assist me if you are familiar with this situation. 

Here is my code

import imaplib
import email
from email.header import decode_header
import webbrowser
import os
import rds_config

# account credentials
username = "myname@enterprise.microsoft.com"
password = "mypassword or app-password"
imap_server = 'outlook.office365.com'

# create an IMAP4 class with SSL 
imap = imaplib.IMAP4_SSL(imap_server, port=993)
# authenticate
imap.login(username, password)

# status, messages = imap.select('"Sent Items"')
status, messages = imap.select('INBOX')
messages = int(messages[0])

Here is the error:

---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
c:\Users\Among\Desktop\Code\UpWork\rodney_projects\lambda_sync_email_to_MYSQL\source\test.ipynb Cell 15 in <cell line: 26>()
     24 imap = imaplib.IMAP4_SSL(imap_server, port=993)
     25 # authenticate
---> 26 imap.login(username, password)
     28 # status, messages = imap.select('"Sent Items"')
     29 status, messages = imap.select('INBOX')

File c:\Users\Among\AppData\Local\Programs\Python\Python39\lib\imaplib.py:612, in IMAP4.login(self, user, password)
    610 typ, dat = self._simple_command('LOGIN', user, self._quote(password))
    611 if typ != 'OK':
--> 612     raise self.error(dat[-1])
    613 self.state = 'AUTH'
    614 return typ, dat

error: b'LOGIN failed.'

Solution

  • You have to use strong authentification now. Microsoft disabled the Basic Auth : https://techcommunity.microsoft.com/t5/exchange-team-blog/basic-authentication-deprecation-in-exchange-online-september/ba-p/3609437

    See this topic for IMAP with XOAUTH : Use IMAP with XOAUTH2 and MS365 Application permissions to authenticate IMAP for a user