使用Exchange中的接口发送邮件

时间:2024-03-06 16:51:37

Exchange账户发送邮件,由于25端口被禁,只能捣鼓别的方法。

需要引入Microsoft.Exchange.WebServices.dll。

1、下载程序集并安装, https://www.microsoft.com/en-us/download/details.aspx?id=28952

2、在程序中引入Microsoft.Exchange.WebServices.dll

3、代码:

public static void SendByExChange(string[] toemails, string[] Ctoemails, string title, string body, string[] fileName)
{
try
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };//至关重要的一句 否则会报错:The Autodiscover service couldn\'t be located.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new NetworkCredential("用户名", "密码");
service.Url = new Uri(@"http://XXX/ews/Exchange.asmx");//exchange服务器上接口地址
service.TraceEnabled = false;
service.AutodiscoverUrl("发件箱");
EmailMessage message = new EmailMessage(service);
message.Subject = title;
message.Body = body;
if (fileName != null)
{
foreach (var str in fileName)
message.Attachments.AddFileAttachment(str);
}
if (Ctoemails != null)
{
foreach (var email in Ctoemails)
message.CcRecipients.Add(email);
}
if (toemails != null)
{
foreach (var email in toemails)
message.ToRecipients.Add(email);
}

message.SendAndSaveCopy();
}
catch (Exception ex)
{
Utility.LogHelper.WriteLog("发送邮件失败", ex);
}
}

相关文章