How to use exchangelib to get mail for non - inbox folders
Asked Answered
E

2

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='[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?

Effete answered 7/2, 2018 at 4:19 Comment(0)
H
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)
Heidyheifer answered 7/2, 2018 at 10:51 Comment(0)
B
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
Blooper answered 9/4, 2019 at 12:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.