1
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.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Lehas123
  • 21
  • 5

1 Answers1

1

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
Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63
  • Thanks for your answer! Just one question, when I run the code without if isinstance(m, Message): everything works fine, but with it my code appends no emails to my created lists. is there maybe another way to check if it is a message or why does it not work? – Lehas123 Nov 13 '22 at 14:17
  • 1
    The easiest is probably to add a `breakpoint()` just before, and check the actual type of the objects returned. – Erik Cederstrand Nov 13 '22 at 19:11
  • If I check for the type it tells me class 'exchangelib.items.message.Message but if isinstance(m, Message): doesnt work. If I say isinstance(m, Messages) with an s it just gives me the empty lists. – Lehas123 Nov 23 '22 at 14:14