Lehas123
Lehas123

Reputation: 21

exchangelib, traverse all folders and only messages

for shared_postbox in shared_postboxes:
    
    account = Account(shared_postbox, credentials=credentials, autodiscover=True)
    top_folder = account.root
    email_folders = [f for f in top_folder.walk() if f.CONTAINER_CLASS == 'IPF.Note']

    for folder in email_folders:
        
        for m in folder.all().only('text_body', 'datetime_received',"subject", "sender", "datetime_received").filter(datetime_received__gt=midnight, sender__exists=True).order_by('-datetime_received'):
            if type(m) == "Message":
                
                do something

I am trying to traverse all folders in with exchangelib. But in the last step when I want to grab the information it tells me

ValueError: Unknown field path 'sender' on folders (AllContacts(Root(<exchangelib.account.Account object at 0x000001DB1EE3CDC0>, '[self]', 'root', 6, 0, 88, None, 'AAMkAGEwOTlhMDY0LTI2YjgtNGVlNy1hNTJkLTVlZDhkYTJhNDc4ZAAuAAAAAACeSUbQ4cDdS7JarMTUomo6AQC67tB7513QQIB5Or1jJmzOAAAAAAEBAAA=', 'AQAAABYAAAC67tB7513QQIB5Or1jJmzOAADjtFs6'), 'AllContacts', 0, 0, 0, 'IPF.Note', 'AAMkAGEwOTlhMDY0LTI2YjgtNGVlNy1hNTJkLTVlZDhkYTJhNDc4ZAAuAAAAAACeSUbQ4cDdS7JarMTUomo6AQC67tB7513QQIB5Or1jJmzOAAAAAFd9AAA=', 'BwAAABYAAAC67tB7513QQIB5Or1jJmzOAAAAABgA'),) in only()

So how can I filter the folders so that only emails are looked into. I want to grab all bodies from all the emails in every folder from the accounts saved in a list.

Upvotes: 1

Views: 623

Answers (1)

Erik Cederstrand
Erik Cederstrand

Reputation: 10220

The error comes from the fact that the list of folders you're searching contains the AllContacts folder which cannot contain items with a sender field.

A better filter for folders containing messages could be:

from exchangelib.folders import Messages

email_folders = [f for f in top_folder.walk() if isinstance(f, Messages)]

Additionally, your if type(m) == "Message": condition is not going to work. Instead, you could do:

from exchangelib import Message

if isinstance(m, Message):
    # Do something

Upvotes: 1

Related Questions