I am working on an Outlook 2007 add-in. I found that some code was sorting through all the folders, but I couldn’t figure out how to loop inside any given folder to check MailItem objects (ultimately, I want to save emails elsewhere and change the .Subject property).
Here is what I still have:
private void btnFolderWalk_Click(object sender, EventArgs e) { // Retrieve the name of the top-level folder (Inbox) , for // the purposes of this demonstration. Outlook.Folder inbox = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) as Outlook.Folder; // Cast the MAPI folder returned as an Outlook folder // Retrieve a reference to the top-level folder. if (inbox != null) { Outlook.Folder parent = inbox.Parent as Outlook.Folder; // the mailbox itself if (parent != null) { RecurseThroughFolders(parent, 0); } } } private void RecurseThroughFolders(Outlook.Folder theRootFolder, int depth) { if (theRootFolder.DefaultItemType != Outlook.OlItemType.olMailItem) { return; } lbMail.Items.Add(theRootFolder.FolderPath); foreach (Object item in theRootFolder.Items) { if (item.GetType() == typeof(Outlook.MailItem)) { Outlook.MailItem mi = (Outlook.MailItem)item; lbMail.Items.Add(mi.Subject); //------------------------------------------------------------------------- // mi.Subject is actually a folder name as it full path. // How to "open it" to get emails? // need loop here to modify .Subject of MailItem(s) in certain subfolders //------------------------------------------------------------------------- } } foreach (Outlook.Folder folder in theRootFolder.Folders) { RecurseThroughFolders(folder, depth + 1); } }
I use listbox at this stage of work, and now the result is as follows. I want to "process" email messages in Projectnnnnnnn folders.
\\Personal Folders \\Personal Folders\Deleted Items \\Personal Folders\Inbox \\Personal Folders\Inbox\MySubFolder \\Personal Folders\Inbox\MySubFolder\Project456212 \\Personal Folders\Inbox\MySubFolder\Project318188 \\Personal Folders\Inbox\Outbox \\Personal Folders\Inbox\SentItems
EDIT:
I fixed this with a slight change to the loop above (i.e. removing the check that the current item is a mail item):
foreach (Object item in theRootFolder.Items) { Outlook.MailItem mi = (Outlook.MailItem)item; string modifiedSubject = "Modifed Subject: " + mi.Subject; lbMail.Items.Add(modifiedSubject); mi.Subject = modifiedSubject; mi.Save();
source share