Search code examples
pythonpython-3.xexchangelib

How to get the parent folder name of Message with Exchangelib python


I have an Item object obtained by filtering on an account using exchangelib in python 3.7. It is an email object. I need to find the parent folder name of this item. I specifically need the name field of the folder(This is for tracking where specific emails are moved in a mailbox).

I can see a field parent_folder_id in the item object which returns what I think is a valid folder id. This is also for a production mailbox where account.root.get_folder(folder_id=idObj) times out due to Exchange settings which I cannot change. Pretty much any request which caches fails with a timeout.

account=Account(...)
mailItems=account.inbox.all().filter(subject="foo")
print([i.parent_folder_id.id for i in mailItems])

This prints a list of folder ids. I need the names of these folders. Unclear how to proceed. Any help would be appreciated


Solution

  • Since you're only searching account.inbox and not its subfolders, parent_folder_id will always point to account.inbox.

    There's not a very good API yet for looking up folders by e.g. ID. The best solution currently is to use a folder QuerySet:

    from exchangelib.folders import SingleFolderQuerySet
    
    f = SingleFolderQuerySet(
        account=account,
        folder=account.root
    ).get(id=i.parent_folder_id.id)