在C#中,使用Exchange Web Services (EWS) 库可以方便地从Exchange服务器接收邮件。以下是一个简单的示例,展示了如何使用EWS接收邮件:
Install-Package Microsoft.Exchange.WebServices.NETStandard -Version 2.2.0
using System;
using System.Net;
using Microsoft.Exchange.WebServices.Data;
namespace ExchangeEmailReceiver
{
class Program
{
static void Main(string[] args)
{
// 设置Exchange服务器的URL和凭据
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.Credentials = new NetworkCredential("username", "password", "domain");
service.Url = new Uri("https://your-exchange-server/ews/exchange.asmx");
// 创建一个搜索过滤器,用于获取未读邮件
SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
// 定义要获取的邮件属性
PropertySet itemPropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Subject, EmailMessageSchema.From, EmailMessageSchema.Body);
// 执行搜索并获取结果
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, itemPropertySet);
// 遍历并输出邮件信息
foreach (Item item in findResults)
{
EmailMessage message = EmailMessage.Bind(service, item.Id, itemPropertySet);
Console.WriteLine($"Subject: {message.Subject}");
Console.WriteLine($"From: {message.From.Name} ({message.From.Address})");
Console.WriteLine($"Body: {message.Body.Text}");
Console.WriteLine("------------------------------");
// 将邮件标记为已读
message.IsRead = true;
message.Update(ConflictResolutionMode.AutoResolve);
}
}
}
}
请注意,你需要将username
、password
、domain
和your-exchange-server
替换为实际的值。此外,根据需要调整Exchange版本和邮件属性。
这个示例将连接到指定的Exchange服务器,使用提供的凭据进行身份验证,然后搜索收件箱中的所有未读邮件。对于每封邮件,它将输出主题、发件人和正文。最后,它将邮件标记为已读。