Want to enumerate Outlook folders

大兔子大兔子 提交于 2020-01-11 09:15:42

问题


I'm looking for some code (C# or VB.NET preferred) to iterate through all folders in an Outlook mailbox and return the names of those folders. I'm not looking to pop up the Outlook folder dialog, but rather to return the folder names in a given mailbox from outside Outlook.

Thanks


回答1:


This is actually quite easy using VSTO (Visual Studio Tools for Office). First Use VSTO to create an Outlook 2007 add in. Here is some of my experimental code that does this.

   private void RecurseThroughFolders(Outlook.Folder theRootFolder, int depth)
    {
        if ( theRootFolder.DefaultItemType != Outlook.OlItemType.olMailItem ) {
            return;
        }

        Console.WriteLine("{0}", theRootFolder.FolderPath);

        foreach( Object item in theRootFolder.Items ) {
            if (item.GetType() == typeof( Outlook.MailItem )) {
                Outlook.MailItem mi = (Outlook.MailItem)item;
                if (mi.Categories.Length > 0) {
                    WriteLinePrefix(depth);
                    Console.WriteLine("  $ {0}", mi.Categories);
                }
            }
        }

        foreach (Outlook.Folder folder in theRootFolder.Folders) {
            RecurseThroughFolders(folder, depth + 1);
        }
    }

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    Outlook.Application olApp = new Outlook.Application();

    Console.WriteLine("Default Profile = {0}", olApp.DefaultProfileName);

    Console.WriteLine("Default Store = {0}", olApp.Session.DefaultStore.DisplayName);

    selectExplorers = this.Application.Explorers;
    selectExplorers.NewExplorer += new Outlook.ExplorersEvents_NewExplorerEventHandler( newExplorer_Event );

    Outlook.Folder theRootFolder  = (Outlook.Folder) olApp.Session.DefaultStore.GetRootFolder();
    RecurseThroughFolders( theRootFolder, 0 );
}



回答2:


I prefer a more LINQ friendly approach:

private IEnumerable<MAPIFolder> GetAllFolders(Folders folders)
{
    foreach (MAPIFolder f in folders) {
        yield return f;
        foreach (var subfolder in GetAllFolders(f.Folders)) {
            yield return subfolder;
        }
    }
}

Then you can peruse the folders any way like. For example:

private IEnumerable<MailItem> GetAllEmail(NameSpace ns)
{
    foreach (var f in GetAllFolders(ns.Folders)) {
        if (f == DELETE_FOLDER) continue;
        if (f.DefaultItemType == OlItemType.olMailItem) {
            // Party!
        }
    }
}


来源:https://stackoverflow.com/questions/861370/want-to-enumerate-outlook-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!