在C#中,使用Exchange服務器發送郵件的方法如下:
首先,確保已安裝Microsoft.Exchange.WebServices
庫。可以通過NuGet包管理器進行安裝。在Visual Studio中,依次點擊“工具”>“NuGet包管理器”>“管理解決方案的NuGet包”,然后搜索并安裝Microsoft.Exchange.WebServices
。
引入必要的命名空間:
using Microsoft.Exchange.WebServices.Data;
public static void SendEmail(string subject, string body, string toAddress)
{
// 創建Exchange服務對象
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
// 設置Exchange服務器的URL
service.Url = new Uri("https://your-exchange-server-url/ews/exchange.asmx");
// 設置身份驗證憑據(使用用戶名和密碼)
service.Credentials = new WebCredentials("username", "password", "domain");
// 創建電子郵件消息
EmailMessage email = new EmailMessage(service);
// 設置收件人、主題和正文
email.ToRecipients.Add(toAddress);
email.Subject = subject;
email.Body = new MessageBody(BodyType.HTML, body);
// 發送電子郵件
email.SendAndSaveCopy();
}
SendEmail
方法發送郵件:string subject = "Test Email";
string body = "<h1>Hello, this is a test email.</h1>";
string toAddress = "recipient@example.com";
SendEmail(subject, body, toAddress);
請注意,您需要將上述代碼中的your-exchange-server-url
、username
、password
和domain
替換為實際的Exchange服務器URL、用戶名、密碼和域名。同時,根據需要修改收件人地址、郵件主題和正文。