
Outlook: Loop over Inbox Items
Hello, this is just a quick code snippet. It demonstrates how to quickly iterate over all Items in the InboxFolder.
There are several ways how you can access the Data within Outlook and it depends on what you want to archive.
One scenario is to quickly get List of Data to fill a List in your application.
In the past you had to use the Outlook ViewControl, or iterate over the Items-Collection in the Folder.
Luckily with Outlook 2007 comes the Table-Object, that gives you direct Table-Access to the underlying MAPIFolder.
Note that the Outlook Object Model is not a relational Database, so the Performance might not be as you expect, especeialy when you still have to load Items via the Object Model. But a good scenario is, to quickly display a list of Items, or filter out some items so that you have to load and process only a few items via the Object Model.
Enough said, here is a code snippet:
private void LoopOverInbox(){
MSOutlook.MAPIFolder olFolder;
MSOutlook.Table folderTable;
MSOutlook.Row folderRow;
MSOutlook.Application olApp = new MSOutlook.Application(); MSOutlook.NameSpace olNs = olApp.GetNamespace("MAPI");olNs.Logon();
// GetTheFolderolFolder = olNs.GetDefaultFolder(MSOutlook.OlDefaultFolders.olFolderInbox);
// Filter only Email Items elder then 3 Monthstring filter = string.Format("[MessageClass]='IPM.Note' AND [LastModificationTime] < '{0}'"
, DateTime.Now.AddMonths(-3));
folderTable = olFolder.GetTable(filter, MSOutlook.OlTableContents.olUserItems);
// Add additional Columns as required for processing or displaying Data folderTable.Columns.Add("Unread");folderTable.MoveToStart();
// In this sample we just fill a simple DictionaryDictionary<string, string> entryIdSubject = new Dictionary<string, string>();
while(!folderTable.EndOfTable) {folderRow = folderTable.GetNextRow();
entryIdSubject[(string) folderRow[1]] = (string) folderRow[2];
}
folderTable = null; olFolder = null;olNs.Logoff();
olNs = null; olApp = null;GC.Collect();
GC.WaitForPendingFinalizers();
foreach (var keyValue in entryIdSubject) {
Trace.WriteLine(string.Format("EntryID: {0} - Subject: {1}"
, keyValue.Key, keyValue.Value));
}
}
Basically this demonstrates how to access the MAPIFolder-Table, add additional columns, set a filter, and loop over the Items.
There are only a few columns available by default.
Links:
The Outlook Table Object: http://msdn.microsoft.com/en-us/library/ff860769.aspx
The Default Table Properties: http://msdn.microsoft.com/en-us/library/ff865868.aspx
Greets – Helmut