8

Hello I am wondering if it is possible to send a search query to Outlook 2010 from my WinForms app. That is, not search the .PST file as I've been searching around and finding, I'm trying to display a list of results in Outlook as if I typed in the search box myself.

If it is possible, any example code would be helpful. Additionally, is it possible to directly perform a search in All Mail Items versus, usually when you do a search it combs the current folder. Thanks.

ikathegreat
  • 2,311
  • 9
  • 49
  • 80

1 Answers1

14

If you want to access the Outlook data (mail for example) you have to add a COM reference to the Microsoft Outlook X.X Object library.

For Outlook you can use COM interop. Open the Add Reference dialog and select the .NET tab, then add a reference to the Microsoft.Office.Interop.Outlook assembly.

enter image description here

Afterwards don't forget to add the namespace "Microsoft.Office.Interop.Outlook" to your using clauses.

Now you can create an instance of the Outlook application object:

Microsoft.Office.Interop.Outlook.Application outlook;
outlook = new Microsoft.Office.Interop.Outlook.Application(); 

Let's perform a query on your inbox:

MAPIFolder folder =
    outlook.GetNamespace("MAPI").GetDefaultFolder(OlDefaultFolders.olFolderInbox);
    IEnumerable<MailItem> mail = 
        folder.Items.OfType<MailItem>().Where(m => m.Subject == "Test").Select(m => m);

You specify the folder you want to search as a parameter for the GetDefaultFolder(...) method. You can specify other folder besides the inbox.

  • olFolderSentMail
  • olFolderOutbox
  • olFolderJunk
  • ...

Check out each possible value on MSDN:

OlDefaultFolders Enumeration

Stefan Cruysbergs created an OutlookProvider component which acts as a wrapper for the Outlook application object. You can use LINQ to query this provider and retrieve data such as the contacts, mail...etc.. Just download his code and check it out. This should be enough to get you started.

Christophe Geers
  • 8,564
  • 3
  • 37
  • 53
  • 1
    hmm this is not quite what I was hoping for. I'm familiar with creating an instance of Outlook, this appears to return back to the application the results of the query. Instead, I would like to simply have Outlook open, provide a search query from my app, and in the open instance (or if not open, start Outlook) show the search results from the provided query. – ikathegreat Jul 09 '12 at 20:04
  • Sounds like you would like to do an instant search (I know, I'm 6 years too late). You can open up outlook and automatically populate the instant search field (however it is limited to 255 characters lol). Look into this: https://msdn.microsoft.com/en-us/library/office/ff424478.aspx – nardnob Jun 14 '18 at 21:18