5

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='test@test.com',
    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?

Οurous
  • 348
  • 6
  • 17
王胖胖
  • 107
  • 1
  • 3
  • 10

2 Answers2

7

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)
Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
4

You can do for inbox children folders only:

for subfolder in account.inbox.children:
    for emailz in subfolder.all().only('subject','attachments','datetime_sent').order_by('-datetime_received'):
        #do your thing

Or all root children folders:

for subfolder in account.root.children:
    for emailz in subfolder.all().only('subject','attachments','datetime_sent').order_by('-datetime_received'):
        #do your thing
Hugo Vares
  • 977
  • 7
  • 7