0

I got that error, credentials is ok and was working in the morning. Reset password did not change, logging into OWA works fine, login using imaplib fails with "LOGIN failed" after 1 minute or so!

def get_otp():
    # sleeping for 20 seconds
    time.sleep(20)
    # username for mail id
    user = '***********'
    # password for email id
    password = '********'

    # hostname for webmail.recogx.ai
    hostname = 'mail.office365.com'
    print("entered hostname ")

    def get_body(msg):
        # id=f message is present in more than one part
        if msg.is_multipart():
            return get_body(msg.get_payload(0))
        else:
            return msg.get_payload(None, True)
    print("bodyyyyyy")
    # entering hostname to enter into session
    # time.sleep(10)
    mail = imaplib.IMAP4_SSL(hostname)
    time.sleep(5)
    print("logged ")
    # logging in page
    print("mail login",mail.login(user, password))
    mail.login(user, password)

    print("logged in")
    # selecting inbox
    mail.select('INBOX')

    # searching unseen messages
    result, data = mail.search(None, 'UNSEEN')

    # finding total mail numbers
    mail_ids = data[0]
    id_list = mail_ids.split()
    latest = id_list[-1]
    print("opt next")
    # fetching data from latest email
    result, data = mail.fetch(latest, '(RFC822)')
    ror = email.message_from_bytes(data[0][1])
    body = get_body(ror)

    # converting text body from byte to string
    body = body.decode("utf-8")
    time.sleep(3)

   
    otp = re.search(r'\d{7}', body).group()

  

Unable to read the OTP.

xxxxxx
  • 9
  • 4
  • Probably a server-side problem then. As an aside, your code seems to be written for Python 3.5 or earlier. The `email` library was overhauled in 3.6 and is now quite a bit more versatile and logical. Probably `from email.policy import default` and pass `policy=default` to `email_from_bytes`. With the modern `EmailMessage` API, there is no need to separately decode the body. (Assuming that the body is UTF-8 is quite likely to break; MIME allows any IANA character set there. But Python will decode it into Unicode for you already.) – tripleee Oct 11 '22 at 06:08
  • 2
    Microsoft disabled cleartext passwords recently (with years of warning). – arnt Oct 11 '22 at 09:36

1 Answers1

1

Microsoft has disabled basic authentication in Office 365:

https://techcommunity.microsoft.com/t5/exchange-team-blog/basic-authentication-deprecation-in-exchange-online-september/ba-p/3609437

However, there might be a method to authenticate using oauth2.

I'm personally working on a solution that might be using: Office 365 IMAP authentication via OAuth2 and python MSAL library

Rusty Weber
  • 1,541
  • 1
  • 19
  • 32