在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、用户名、密码和域名。同时,根据需要修改收件人地址、邮件主题和正文。