Reading Messages in a Folder

Before you can open messages in a folder, you must open the information store and the folder itself. See Opening an Information Store, Opening an Existing Public Folder, and Opening an Existing Private or Personal Folder.

    To read the messages in a folder
  1. Open the folder contents table, using the IMAPIFolder::GetContentsTable method.
  2. Set the columns of the contents table to specify which properties are to be retrieved for each message. One of the properties to retrieve is PR_ENTRYID because you will use it in step 4. .
  3. Query the contents table by calling the MAPI HrQueryAllRows function or the IMAPITable::QueryRows method.
  4. Open a message with a call to the MAPI OpenEntry method.
  5. After opening the message, you can choose to indicate that the message has been read.

The following sample code illustrates these steps.

// Open folder contents table.
hr = lpFolder->GetContentsTable(
    MAPI_DEFERRED_ERRORS,
    &lpFolderTable);

// Here we're primarily interested in ENTRYIDs, and wish to sort by submission time.
    static SizedSPropTagArray( 1L, PropEntryID) = { 1L, {PR_ENTRYID}};
    static SizedSSortOrderSet( 1L, SortSubmitTime) =
    { 1L, 0L, 0L, { PR_CLIENT_SUBMIT_TIME, TABLE_SORT_ASCEND}};

// Read table.  If you perform this action inside a loop, you may 
   wish to use the MAPI
// SetColumns and SortTable functions before this call.  They only 
   need to be performed
// once when the contents table is retrieved.
hr = HrQueryAllRows(
    lpFolderTable,
    (LPSPropTagArray)&PropEntryID,
    NULL,           // no restriction
    (LPSSortOrderSet)&SortSubmitTime,
    NULL,
    0L,
    &lpMessageRows);

// Read rows one at a time
ULONG i = 0L;
ULONG ulObjType = 0L;
LPMESSAGE lpMessage = NULL;
for (i = 0L; i < lpMessageRows->cRows; i++)
{
    // Open the message    
    hr = lpFolder->OpenEntry(
        0L,
        lpMessageRows->aRow[i].lpProp[0].bin.cb,
        lpMessageRows->aRow[i].lpProp[0].bin.lpb,
        NULL,
        MAPI_MODIFY | MAPI_DEFERRED_ERRORS,
        &ulObjType,
        (LPUNKNOWN*)&lpMessage);

    // Indicate this message has been read
    hr = lpMessage->SetReadFlag( MAPI_DEFERRED_ERRORS);

    //
    // Perform message processing here...
    //

    // Delete the message
    hr = lpFolder->DeleteMessage(
        lpMessageRows->aRow[i].lpProp[0].bin, 
        0L,
        NULL,
        0L);
}