Edit

Share via


Programmatically search within a specific folder

This code example uses the Find and FindNext methods to search for text in the subject field of e-mail messages that are in the Inbox. This method uses a string filter to check for the letter T as the starting letter of the Subject text.

Applies to: The information in this topic applies to VSTO Add-in projects for Outlook. For more information, see Features available by Office application and project type.

Example

private void SearchInBox()
{
    Outlook.Folder inbox = this.Application.ActiveExplorer().Session.
        GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
    Outlook.Items items = inbox.Items;
    Outlook.MailItem mailItem = null;
    object folderItem;
    string subjectName = string.Empty;
    string filter = "[Subject] > 's' And [Subject] <'u'";
    folderItem = items.Find(filter);
    while (folderItem != null)
    {
        mailItem = folderItem as Outlook.MailItem;
        if (mailItem != null)
        {
            subjectName += "\n" + mailItem.Subject;
        }
        folderItem = items.FindNext();
    }
    subjectName = " The following e-mail messages were found: " +
        subjectName;
    MessageBox.Show(subjectName);
}