Perform search query in Outlook

2020-06-17 06:06发布

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.

1条回答
够拽才男人
2楼-- · 2020-06-17 06:27

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.

查看更多
登录 后发表回答