如何将 Outlook 电子邮件搜索结果存储到 IEnumerable 对象 (C#) 中



如何将以下所有(Outlook.Items.Find(结果存储/转换为IEnumerable对象? *展望 16.0

Outlook.MailItem emailResults = null;
emailResults = mailItems.Find($"[Categories] = 'Important'"); 

我正在尝试以下内容,但没有成功。

application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
nameSpace = application.GetNamespace("mapi");
inbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
mailItems = inbox.Items;
IEnumerable<Outlook.MailItem> emailResults = null;
emailResults = (IEnumerable<Outlook.MailItem>)mailItems.Find($"[Categories] = 'Important'");

我试图花哨,而不是迭代每个结果。提前感谢您的任何建议。

使用Items.Restrict- 它返回可枚举Items集合。

感谢德米特里·斯特雷布莱琴科的快速回答!这是我使用解决方案的代码。

using System.Collections.Generic;
using System.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace oMailBoard
{
public static class GetMail
{
public static void SearchOutLook()
{
Outlook.Application application = null;
Outlook.NameSpace nameSpace = null;
Outlook.MAPIFolder inbox = null;
Outlook.Items mailItems = null;
IEnumerable<Outlook.MailItem> emails = null;
string filter = "";
filter = $"[Categories] = 'Important'"; //Exact match
filter = $"@SQL=urn:schemas:httpmail:subject like '%database%'"; //Like match
if (Process.GetProcessesByName("Outlook").Count() > 0) //Is Outlook Open?
{
application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
nameSpace = application.GetNamespace("mapi");
inbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
mailItems = inbox.Items;
//Store results into a numerable varible.
emails = mailItems.Restrict(filter).Cast<Outlook.MailItem>(); 
//Now I can iterate though the results. 
foreach (Outlook.MailItem e in emails)
{
Debug.WriteLine("f");                  
Debug.WriteLine(e.Subject);                     
}
Debug.WriteLine(emails.Count());
Marshal.ReleaseComObject(inbox);
Marshal.ReleaseComObject(nameSpace);
Marshal.ReleaseComObject(application);
inbox = null;
nameSpace = null;
application = null;
}
else
{
Debug.WriteLine("Outlook Not Open!");
}    
}        
}
}

相关内容

最新更新