The following task arose: unload all messages in the inbox, outbox, user folders, subfolders, as well as in attachments in which a certain word (for example, "shovel"), certain (several previously known ) mailboxes. Further, the selection (for each user separately) must be saved /exported to a .pst file for further transfer to other software (all actions take place in a corporate environment with a corporate mail server)

Using the exchangengelib library, I connected to the server, logged in with my credentials (to my mailbox), and implemented a message search mechanism.

How do I save the result to a .pst file? Rummaging through a pile of well-known mailboxes (it is clear that you need a u /s with super-rights (which))? Not really, whether it is necessary to separately sort through folders with mail of subfolders. For example, there is an "inbox" folder, there are several letters in it, as well as a subfolder "xxxx" in this folder, and it also contains letters.

Why the question was included in the implementation of this task by a script -as I was told by means of ms exchange, you can download only the first 250 letters from any mailbox.

from exchangelib import DELEGATE, Account, Credentials, Configuration
import keyring
import re
def connect_to_exchange(username, server, mailbox):
    pass_= keyring.get_password("post", "xxxxxxxxx")
    creds= Credentials(username=username, password=pass_)
    config= Configuration(server=server, credentials=creds)
    account= Account(primary_smtp_address=mailbox, autodiscover=False, config=config, access_type=DELEGATE)
    return account
if __name__== '__main__':
    a= connect_to_exchange('xxxxxxxxxx','yyyyyyyyyyyyyyyy','[email protected]')
    start_folder= a.root/'Корневой уровень хранилища' # отсюда начинаю поиск
    for sub_folder in start_folder.children:
        for email in sub_folder.all()[:5]:
            if re.search("лопата", str(email.text_body)):


I hope I explained it clearly. I propose to discuss further actions with you. It is not clear what to do with attachments in the letter, they may also contain the desired word, and also the type of attachment can be any.

Didn't work with exchangelib at all, but I believe that: (1) either you have to go through all users one at a time, or somehow map all user mailboxes to one account; (2) parsing attachments is a bit of a challenge, especially considering the bunch of possible types of documents and archives; (3) how to save emails -you can look here: github.com/ecederstrand/exchangelib/issues/143

Alex2021-10-14 04:27:11

Well, and (4): there is an opinion that it might be worth trying a fundamentally different approach -for example, like here: community.spiceworks.com/topic/... and techgenix.com/...

Alex2021-10-14 04:27:11