Last active
January 13, 2023 09:46
-
-
Save attibalazs/d4c0f9a1d21a0b24ff375690fbb9f9a7 to your computer and use it in GitHub Desktop.
Python functions for creating outlook data files .pst files for archiving emails using win32com.client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# code based on https://mail.python.org/pipermail/python-list/2015-November/698551.html | |
def find_pst_folder(mapi, pst_filepath): | |
dispatch = win32com.client.gencache.EnsureDispatch | |
for store in dispatch(mapi.Stores): | |
if store.IsDataFileStore and store.FilePath == pst_filepath: | |
return store.GetRootFolder() | |
def get_pst_folder(pst_filepath): | |
"""Returns the PST archive folder, if it doesn't exist it creates it""" | |
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") | |
const = win32com.client.constants | |
# get pst folder | |
pst_folder = find_pst_folder(outlook, pst_filepath) | |
# if not found | |
if not pst_folder: | |
outlook.AddStoreEx(pst_filepath, const.olStoreDefault) | |
pst_folder = find_pst_folder(outlook, pst_filepath) | |
# add archive folder | |
pst_folder.Folders.Add('Archive') | |
# set the account name | |
path_list = str.split(pst_filepath, '\\') | |
displayname = path_list[len(path_list)-1].replace('.pst', '') | |
pst_folder.Name = displayname | |
if not pst_folder: | |
raise RuntimeError("Can't find PST folder at %s" % pst_filepath) | |
# return archive folder | |
# archive_folder = pst_folder.GetDefaultFolder.Folders('Archive') | |
return pst_folder |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment