Home > OS >  Loop on outlook folders and save all emails into local drive
Loop on outlook folders and save all emails into local drive

Time:05-13

I now know I can specify emails from which Outlook folder to save to my local drive using the following code:

inbox = outlook.GetDefaultFolder(6).Folder("Inbox").Folder("folder name").Folder("sub-folder name")

Additional query: Is it possible to specify to save emails from ALL Outlook folder to my local drive?

Thank you!

from win32com.client import Dispatch
import os
import re
os.chdir("c:/Users/username/Desktop/Emails")

def save_emails():
    for message in inbox.Items:
        if message.Class == 43:
            name = str(message.Subject)
            # to eliminate any special characters in the name
            name = re.sub('[^A-Za-z0-9] ', '', name)   '.msg'
            # to save in the current working directory
            message.SaveAs(os.getcwd()   '//'   name)


if __name__ == '__main__':
    outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
    inbox = outlook.GetDefaultFolder(6)
    save_emails()

CodePudding user response:

Example

from win32com.client import Dispatch
import os
import re


def save_emails():
    for folder in inbox.Folders:
        print(folder.Name)
        for message in folder.Items:
            print(message.Subject)
            if message.Class == 43:
                name = str(message.Subject)
                # to eliminate any special characters in the name
                name = re.sub('[^A-Za-z0-9] ', '', name)   '.msg'
                # to save in the current working directory
                message.SaveAs(os.getcwd()   '//'   name)


if __name__ == '__main__':
    outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
    inbox = outlook.GetDefaultFolder(6)
    save_emails()

CodePudding user response:

Yes, it is possible to save all items from all folders. You can iterate over all folder recursively in the code and repeat the same actions with each folder. Here is C# example how you could do that (the Outlook object model is common for all kind of programming languages):

private void EnumerateFoldersInDefaultStore()
{
    Outlook.Folder root =
        Application.Session.
        DefaultStore.GetRootFolder() as Outlook.Folder;
    EnumerateFolders(root);
}

// Uses recursion to enumerate Outlook subfolders.
private void EnumerateFolders(Outlook.Folder folder)
{
    Outlook.Folders childFolders =
        folder.Folders;
    if (childFolders.Count > 0)
    {
        foreach (Outlook.Folder childFolder in childFolders)
        {
            // Write the folder path.
            Debug.WriteLine(childFolder.FolderPath);
            // Call EnumerateFolders using childFolder.
            EnumerateFolders(childFolder);
        }
    }
}              

See Enumerate folders for more information.

  • Related