代码之家  ›  专栏  ›  技术社区  ›  Matthew

要枚举Outlook文件夹

  •  4
  • Matthew  · 技术社区  · 17 年前

    我正在寻找代码(C或VB.NET首选),以便遍历Outlook邮箱中的所有文件夹并返回这些文件夹的名称。我不想弹出“Outlook文件夹”对话框,而是从外部Outlook返回给定邮箱中的文件夹名称。

    谢谢

    2 回复  |  直到 16 年前
        1
  •  7
  •   Foredecker    17 年前

    这实际上很容易使用 VSTO (Visual Studio Office工具)。首先使用vsto创建一个outlook 2007外接程序。这是我的一些实验代码。

       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
  •  3
  •   Ray    17 年前

    我更喜欢更友好的LINQ方法:

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

    然后你可以随意浏览文件夹。例如:

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