在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