在C#中,使用Exchange Web Services (EWS) 可以實現郵件搜索。以下是一個簡單的示例,展示了如何使用EWS搜索指定郵箱中的郵件:
首先,確保已安裝Microsoft.Exchange.WebServices NuGet包。在Visual Studio中,可以通過以下步驟安裝:
然后,參考以下代碼示例:
using System;
using Microsoft.Exchange.WebServices.Data;
namespace ExchangeMailSearch
{
class Program
{
static void Main(string[] args)
{
// 設置Exchange服務器的URL和憑據
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.Url = new Uri("https://your-exchange-server/ews/exchange.asmx");
service.Credentials = new WebCredentials("username", "password", "domain");
// 創建搜索過濾器
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), // 僅搜索未讀郵件
new SearchFilter.ContainsSubstring(ItemSchema.Subject, "關鍵詞") // 郵件主題包含“關鍵詞”
);
// 創建郵件屬性集合,以獲取郵件的更多信息
PropertySet itemPropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Subject, EmailMessageSchema.DateTimeReceived);
// 搜索郵件
FindItemsResults<Item> searchResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, itemPropertySet);
// 輸出搜索結果
Console.WriteLine($"找到 {searchResults.TotalCount} 封符合條件的郵件:");
foreach (Item item in searchResults)
{
EmailMessage message = EmailMessage.Bind(service, item.Id, itemPropertySet);
Console.WriteLine($"[{message.DateTimeReceived}] - {message.Subject}");
}
}
}
}
請注意,您需要將上述代碼中的以下內容替換為您自己的Exchange服務器信息和憑據:
https://your-exchange-server/ews/exchange.asmx
:您的Exchange服務器URL。username
:用于登錄Exchange服務器的用戶名。password
:用于登錄Exchange服務器的密碼。domain
:用戶所在的域。此外,您還可以根據需要修改搜索過濾器以搜索符合特定條件的郵件。有關更多EWS搜索過濾器和屬性的信息,請參閱官方文檔:https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-use-search-filters-with-ews-in-exchange