2012年3月21日 星期三

ASP.Net 要透過加入 AD 的 ExchangeServer 發郵件的方法

1. 讓 ASP.Net 信任 ExchangeServer 的自訂憑證

在 Global.asax.cs 裡面的 Application_Start 事件加入以下這行:

ServicePointManager.ServerCertificateValidationCallback += 
    new RemoteCertificateValidationCallback(ValidateServerCertificate);

以及在 Global.asax.cs 加入這個靜態方法

public static bool ValidateServerCertificate(Object sender, 
    X509Certificate certificate, X509Chain chain, 
    SslPolicyErrors sslPolicyErrors)
{
    return true;
}

using 要加入

using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

2. 發郵件時程式

SmtpClient sc = new SmtpClient();
sc.Credentials = CredentialCache.DefaultNetworkCredentials;
sc.EnableSsl = true;
sc.Send(mm);    // mm 是 MailMessage

3. 在 web.config 中設定好

<system.net>
    <mailSettings>
        <smtp from="寄信人信箱" deliveryMethod="Network">
            <network host="郵件主機"
                port="埠號"
                userName="登入帳號"
                password="登入密碼"
                defaultCredentials="true" />
        </smtp>
    </mailSettings>
</system.net>

4. 將 IIS 的應用程式集區設定為「整合式」