Python reading email from outlook account using imaplib/imapclient vs exchangelib?

5.4k Views Asked by At

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?

1

There are 1 best solutions below

2
On

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