0

I am setting up a script to read incoming emails from an outlook.com account and I've tested a few approaches with imaplib and was unsuccessful. Yet when I tried with Exchangelib I was able to do this. I'm not entirely sure why Exchangelib works and imaplib doesn't. I feel like I might be breaking some best practices here as I don't know how Exchangelib is able to connect to the mailbox through some sort of trickery of network connections?

For reference the IMAP code that doesn't work (though it works when I attempt to connect to my personal gmail account)

from imapclient import IMAPClient
import mailparser

with IMAPClient('outlook.office365.com', ssl=True) as server:
    server.login("username", "password")
    server.select_folder('INBOX')
    messages = server.search(['FROM', ])

    # for each unseen email in the inbox
    for uid, message_data in server.fetch(messages, 'RFC822').items():
        email_message = mailparser.parse_from_string(message_data[b'RFC822'])
        print("email ", email_message)

I get the below error

imapclient.exceptions.LoginError: b'LOGIN failed.'

When I use exchangelib it works succesfully. Reference code below:

from exchangelib import Credentials, Account

credentials = Credentials("username", "password")
account = Account(username, credentials=credentials, autodiscover=True)

for item in account.inbox.all().order_by('-datetime_received')[:100]:
    print(item.subject, item.sender, item.datetime_received)

Is there any reason why I can't connect with imaplib/imapclient vs exchangelib? Perhaps some security related reason that I'm not aware of?

alex
  • 1,905
  • 26
  • 51
  • exchangelib might be OAuth aware. Your admin may have set different security settings for EWS (used by exchangelib) vs IMAP (used by imaplib). Have you tried using an app specific password or similar, or using ADAL libraries and registering for OAuth access? – Max Mar 19 '20 at 14:43
  • No I have not tried the app specific password or using ADAL libraries. Thanks for the nod - I will look into EWS between IMAP. Maybe I can reach out to an admin and get some info. – alex Mar 19 '20 at 18:00

1 Answers1

1

I think you might need to pass in the full email-ID when using imapclient/imaplib vs just the username when using exchangelib.

gandhiv
  • 61
  • 4
  • 1
    Thanks for your comment I'm definitely passing it in. Just meant here that `username` being shorthand for `username@domain.com` – alex Mar 22 '20 at 01:47
  • 1
    Oh okay! I still have trouble imagining that the issue is with admin restrictions, although entirely possible. Using imaplib, this works for me: `from imaplib import IMAP4_SSL` `box = IMAP4_SSL('outlook.office365.com', 993)` `box.login(emailID, emailPassword)` I would've said you needed to pass in the outlook imap port, but that would've given you a different error. Best of luck! – gandhiv Mar 22 '20 at 02:02