Eugene Astafiev

How To: Get unread Outlook e-mail items from the Inbox folder

In my previous articles we discussed the Find, FindNext and Restrict methods of the Outlook Items class. You can use these methods for retrieving unread items in the way I did.

In the How to use Find and FindNext methods to retrieve Outlook mail items from a folder article I described the Find and FindNext methods. Here is the code to call the FindAllUnreadEmails method, which gets all unread items one-by-one from the Inbox folder:

C#:

Outlook.NameSpace ns = OutlookApp.GetNamespace("MAPI");
Outlook.MAPIFolder folderInbox = ns.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderInbox);
FindAllUnreadEmails(folderInbox);
if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
if (ns != null) Marshal.ReleaseComObject(ns);

VB.NET:

Dim ns As Outlook.NameSpace = OutlookApp.GetNamespace("MAPI")
Dim folderInbox As Outlook.MAPIFolder = ns.GetDefaultFolder( _
Outlook.OlDefaultFolders.olFolderInbox)
FindAllUnreadEmails(folderInbox)
If Not IsNothing(folderInbox) Then Marshal.ReleaseComObject(folderInbox)
If Not IsNothing(ns) Then Marshal.ReleaseComObject(ns)

In the How to use Restrict method to retrieve Outlook mail items from a folder article I showed the Restrict method in action. Here is the code I used to call the RestrictUnreadItems method, which gets all unread items from the Inbox folder and iterates over them:

C#:

Outlook.NameSpace ns = OutlookApp.GetNamespace("MAPI");
Outlook.MAPIFolder folderInbox = ns.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderInbox);
RestrictUnreadItems(folderInbox);
if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
if (ns != null) Marshal.ReleaseComObject(ns);

VB.NET:

Dim ns As Outlook.NameSpace = OutlookApp.GetNamespace("MAPI")
Dim folderInbox As Outlook.MAPIFolder = ns.GetDefaultFolder( _
Outlook.OlDefaultFolders.olFolderInbox)
RestrictUnreadItems(folderInbox)
If Not IsNothing(folderInbox) Then Marshal.ReleaseComObject(folderInbox)
If Not IsNothing(ns) Then Marshal.ReleaseComObject(ns)

The code for VSTO based add-ins is identical: you just need to use the Application property instead of the OutlookApp one.

I would recommend using the Find and FindNext methods if you have a small number of Outlook items in the collection (see the Items.Count property). On the other hand, the Restrict method works faster than Find/FindNext methods if there is a large number of items in the collection and only a few items are expected to be found.

See you on our forums and in the e-mail support!

2 Comments

Post a comment

Have any questions? Ask us right now!