Want to list Outlook folders

I am looking for some code (preferably C # or VB.NET) to iterate over all folders in an Outlook mailbox and return the names of these folders. I do not want to pop up the Outlook folder dialog box, but rather return the folder names in the specified mailbox from external Outlook.

thanks

+4
source share
2 answers

It is quite simple using VSTO (Visual Studio Tools for Office). First use VSTO to create Outlook 2007. Here are some of my experimental codes that do 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 ); } 
+7
source

I prefer the more convenient LINQ 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 browse folders in any way. For instance:

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

All Articles