You need to use the Find/FindNext or Restrict methods of the Items
class. For example, to get items with Hello world
subject line you can to use the following code:
private void FindAllUnreadEmails(Outlook.MAPIFolder folder)
{
string searchCriteria = "[Subject] = `Hello world`";
StringBuilder strBuilder = null;
int counter = default(int);
Outlook._MailItem mail = null;
Outlook.Items folderItems = null;
object resultItem = null;
try
{
if (folder.UnReadItemCount > 0)
{
strBuilder = new StringBuilder();
folderItems = folder.Items;
resultItem = folderItems.Find(searchCriteria);
while (resultItem != null)
{
if (resultItem is Outlook._MailItem)
{
counter++;
mail = resultItem as Outlook._MailItem;
strBuilder.AppendLine("#" + counter.ToString() +
"\tSubject: " + mail.Subject);
}
Marshal.ReleaseComObject(resultItem);
resultItem = folderItems.FindNext();
}
if (strBuilder != null)
Debug.WriteLine(strBuilder.ToString());
}
else
Debug.WriteLine("There is no match in the "
+ folder.Name + " folder.");
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
if (folderItems != null) Marshal.ReleaseComObject(folderItems);
}
}
Read more about these methods in the following articles:
Also, you may find the AdvancedSearch method of the Application class helpful. The key benefits of using the AdvancedSearch
method in Outlook are:
- The search is performed in another thread. You don’t need to run another thread manually since the AdvancedSearch method runs it automatically in the background.
- Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).
- Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).
- You can stop the search process at any moment using the Stop method of the Search class.
Read more about this method in the Advanced search in Outlook programmatically: C#, VB.NET article.