Outlook: Loop over Inbox Items

Tags: outlook, vsto, download

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");
    // GetTheFolder
    olFolder = olNs.GetDefaultFolder(MSOutlook.OlDefaultFolders.olFolderInbox);
    // Filter only Email Items elder then 3 Month
    string 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
    // In this sample we just fill a simple Dictionary
    Dictionary<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 = null;
    olApp = null;
    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.


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

Add a Comment