C#連接Exchange 發送郵件代碼如下
/// <summary>
/// exchange群發郵件
/// </summary>
/// <param name="credentialUserName">exchange用戶名 [example: test]</param>
/// <param name="credentialUserPwd">exchange用戶密碼</param>
/// <param name="fromEmail">發送人地址 [example: test@allbring.com]</param>
/// <param name="recipientEmail">收件人地址</param>
/// <param name="domainName">郵件域名 [example: mail.allbring.com]</param>
/// <param name="subjectName">郵件主題</param>
/// <param name="bodyVal">郵件內容</param>
/// <param name="isHtml">是否為html</param>
/// <param name="fileArray">發送上傳的路徑</param>
/// <returns></returns>
/// 開發人員:ZJ
public static bool SendExchangeEmails(string credentialUserName, string credentialUserPwd, string fromEmail, List<string> recipientEmail, string domainName, string subjectName, string bodyVal, bool isHtml, string[] fileArray)
{
try
{
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(fromEmail);
foreach (string item in recipientEmail)
{
message.To.Add(item);
}
message.From = fromAddress;
message.Subject = subjectName;
message.Body = bodyVal;
message.IsBodyHtml = isHtml;
if (fileArray != null)
{
for (int i = 0; i < fileArray.Length; i++)
{
//為郵件創建文件附件
Attachment attr = new Attachment(fileArray[i], MediaTypeNames.Application.Octet);
//添加郵件時間戳信息
ContentDisposition conDispositon = attr.ContentDisposition;
conDispositon.CreationDate = System.IO.File.GetCreationTime(fileArray[i]);//文件的創建日期
conDispositon.ModificationDate = System.IO.File.GetLastWriteTime(fileArray[i]);//文件的修改日期
conDispositon.ReadDate = System.IO.File.GetLastAccessTime(fileArray[i]);//文件的讀取日期
//給郵件添加附件
message.Attachments.Add(attr);
}
}
SmtpClient smtpClient = new SmtpClient();
smtpClient.Timeout = 50000;
smtpClient.Host = domainName;
smtpClient.Port = 25;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(credentialUserName, credentialUserPwd);
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(message);
smtpClient.Dispose();
return true;
}
catch (Exception)
{
return false;
}
}
如果exchange服務器只做了證書,在發送郵件的機器上也要安裝證書郵件才能發送出去。
參考地址:https://social.technet.microsoft.com/Forums/en-US/d37c7e8a-6d42-498a-bad4-5eb0ab7e9d40/connecting-to-exchange-server-using-c-to-send-an-email?forum=exchangesvrdevelopment
http://www.systemnetmail.com/faq/2.4.aspx
