How to use exchangelib to get mail for non - inbox folders

王胖胖 picture 王胖胖 · Feb 7, 2018 · Viewed 7.2k times · Source

I want to get mail for non-inbox folders - how can I do this?

I can get the inbox folder's emails like so:

from exchangelib import DELEGATE, Account, Credentials, EWSDateTime

creds = Credentials(
    username='xxx.test.com\test',
    password='123456')
account = Account(
    primary_smtp_address='[email protected]',
    credentials=creds,
    autodiscover=True,
    access_type=DELEGATE)

# Print first 100 inbox messages in reverse order
for item in account.inbox.all().order_by('-datetime_received')[:100]:
    # print(item.subject, item.body, item.attachments)
    print(item.subject)

Giving:

hahaha
heiheihei
pupupu
bibibib
........

And when I get my folders:

from exchangelib.folders import Messages

for f in account.folders[Messages]:
    print f

Messages (aaa)
Messages (bbb)
Messages (ccc)

How can I get the emails out of the ccc folder using Python?

Answer

Erik Cederstrand picture Erik Cederstrand · Feb 7, 2018

Have a look at the folder navigation options in recent versions of exchangelib: https://github.com/ecederstrand/exchangelib#folders

You can print the entire folder structure like this:

print(account.root.tree())

and then navigate to a specific folder using the same syntax as pathlib:

some_other_folder = account.inbox / 'some_inbox_subfolder'
# Or:
some_other_folder = account.root / 'some' / 'other' / 'path'
for item in some_other_folder.all().order_by('-datetime_received')[:100]:
    print(item.subject)