How to: Filter and Efficiently Enumerate Items in a Folder

This example shows how to use the Table object to filter for items in the Inbox that have attachments, and efficiently enumerate such items, displaying selected properties for each item.

The code sample specifies the property PR_HASATTACH with the MAPI namespace, and uses the property to create the initial filter in the GetTable method on the Inbox. A Table object for an item type has default columns representing certain properties of that item type. To customize the columns, this example first calls the RemoveAll method on the Columns collection of that Table, and then calls the Add method on the Columns collection to add the EntryID, Subject, and ReceivedTime properties using the built-in property names, with the ReceivedTime column storing values in local date-time representation. The example then calls Columns.Add one more time to add the ReceiveTime property specifying its MAPI namespace so that this column will store the value as a Universal Coordinated Time (UTC) date-time value. Finally, the example enumerates each item in the Table, displaying the value of each of the four properties specified as the table columns.

If you use Microsoft Visual Studio to test this code example, you must first add a reference to the Microsoft Outlook 14.0 Object Library component and specify the Outlook variable when you import the Microsoft.Office.Interop.Outlook namespace. The Imports or using statement must not occur directly before the functions in the code example but must be added before the public Class declaration. The following lines of code show how to do the import and assignment in Visual Basic and C#.

Imports Outlook = Microsoft.Office.Interop.Outlook
Private Sub DemoTableColumns()
    Const PR_HAS_ATTACH As String = _
    ' Obtain Inbox
    Dim folder As Outlook.Folder = _
        CType(Application.Session.GetDefaultFolder( _
        Outlook.OlDefaultFolders.olFolderInbox), _
    ' Create filter
    Dim filter As String = "@SQL=" & Chr(34) _
        & PR_HAS_ATTACH & Chr(34) & " = 1"
    Dim table As Outlook.Table = _
        folder.GetTable(filter, _
    ' Remove default columns
    ' Add using built-in name
    table.Sort("ReceivedTime", Outlook.OlSortOrder.olDescending)
    ' Add using namespace
    ' Date received
    table.Columns.Add( _
    While Not (table.EndOfTable)
        Dim nextRow As Outlook.Row = table.GetNextRow()
        Dim sb As StringBuilder = New StringBuilder()
        ' Reference column by name 
        sb.AppendLine("Received (Local): " _
            & nextRow("ReceivedTime").ToString())
        ' Reference column by index
        sb.AppendLine("Received (UTC): " & nextRow(4).ToString())
    End While
End Sub

Other Resources