在C#中,使用Exchange Web Services (EWS) API實現郵件轉發。以下是一個簡單的示例,展示了如何將收到的郵件轉發給另一個收件人:
首先,確保已安裝Microsoft.Exchange.WebServices NuGet包。在Visual Studio中,可以通過以下步驟安裝:
接下來,編寫以下代碼:
using System;
using Microsoft.Exchange.WebServices.Data;
namespace ExchangeMailForwarder
{
class Program
{
static void Main(string[] args)
{
// 用你的Exchange服務器地址和用戶憑據替換這些值
string exchangeUrl = "https://your-exchange-server/ews/exchange.asmx";
string emailAddress = "your-email@example.com";
string password = "your-password";
// 創建ExchangeService對象并設置憑據
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.Credentials = new WebCredentials(emailAddress, password);
service.Url = new Uri(exchangeUrl);
// 創建一個搜索篩選器,以便只獲取未讀郵件
SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
// 獲取收件箱中的未讀郵件
FindItemsResults<Item> unreadMail = service.FindItems(WellKnownFolderName.Inbox, searchFilter, new ItemView(10));
foreach (EmailMessage email in unreadMail)
{
// 加載郵件正文和其他屬性
email.Load();
// 創建一個新的郵件,用于轉發
EmailMessage forwardEmail = new EmailMessage(service);
forwardEmail.Subject = email.Subject;
forwardEmail.Body = email.Body;
// 添加收件人
forwardEmail.ToRecipients.Add("recipient@example.com");
// 發送轉發的郵件
forwardEmail.SendAndSaveCopy();
// 標記原始郵件為已讀
email.IsRead = true;
email.Update(ConflictResolutionMode.AutoResolve);
}
}
}
}
請注意,您需要將exchangeUrl
、emailAddress
和password
變量替換為您的Exchange服務器地址和用戶憑據。此外,您還需要將recipient@example.com
替換為要將郵件轉發到的收件人地址。
這個示例將連接到Exchange服務器,查找收件箱中的未讀郵件,然后將這些郵件轉發給指定的收件人。同時,它還會將原始郵件標記為已讀。