Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 698
王胖胖 Avatar asked Dec 13 '22 18:12

王胖胖


1 Answers

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)
like image 124
Erik Cederstrand Avatar answered Dec 18 '22 00:12

Erik Cederstrand