在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服務器,使用提供的憑據進行身份驗證,然后搜索收件箱中的所有未讀郵件。對于每封郵件,它將輸出主題、發件人和正文。最后,它將郵件標記為已讀。