2021年11月29日 星期一

[研究][ASP.NET]不能為收取目錄傳遞方法啟用 SSL。

[研究][ASP.NET]不能為收取目錄傳遞方法啟用 SSL。

SSL must not be enabled for pickup-directory delivery methods.

2021-11-29

因為 Web.config 中設定 


<system.net>
    <mailSettings>
      <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="C:\inetpub\mailroot\Pickup" />
      </smtp>
    </mailSettings>
</system.net>

解決:請在 client.Send(message); 之前加上  


client.DeliveryMethod = SmtpDeliveryMethod.Network;

範例


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

protected void Button3_Click(object sender, EventArgs e)
{
    MailMessage message = new MailMessage(寄件者Email, 收件者Email)
    {
        Subject = "測試主旨-測試一般郵件(SSL連線、Fortify SCA驗證通過)",
        Body = "本文",
        SubjectEncoding = Encoding.UTF8,
        BodyEncoding = Encoding.UTF8,
        IsBodyHtml = true
    };
    try
    {
        //SmtpClient client = new SmtpClient();
        SmtpClient client = new SmtpClient("localhost", 25);
        //SmtpClient client = new SmtpClient(SMTP伺服器, 25);

        //client.ServicePoint.MaxIdleTime = 1;
        //client.ServicePoint.ConnectionLimit = 1;

        //Fortify SCA : Critical : Insecure Transport Mail Transmission
        //需用加密連線,加上 client.UseDefaultCredentials = true; 和 client.EnableSsl = true;

        // 只有 client.UseDefaultCredentials = true; 一個寄信成功,但是 Fortify SCA 會報告
        client.UseDefaultCredentials = true;    // OK

        // 根據驗證程序,遠端憑證是無效的。=> 會出錯,下面這一行必須註解掉
        // 原因:mail server和client使用ssl連線,但ssl憑證並沒有經過認證(ex:自簽憑證 Self Signed Certifcate)
        // client.EnableSsl = true;

        // 解決「根據驗證程序,遠端憑證是無效的。」,不管驗證結果 true 或 false,都當 true
        //ServicePointManager.ServerCertificateValidationCallback +=  (sender, cert, chain, sslPolicyErrors) => true;
        //ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
        //System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
        System.Net.ServicePointManager.ServerCertificateValidationCallback = CertificateCheck;
        client.EnableSsl = true;

        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.Send(message);
        Response.Write("寄件成功");
    }
    catch (Exception)
    {
        Response.Write("寄件失敗");

        //不能為收取目錄傳遞方法啟用 SSL。
        //SSL must not be enabled for pickup-directory delivery methods.
        throw;
    }
}
private static bool CertificateCheck(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return !certificate.Issuer.Equals("解決");
    // or
    //return false;
}

(完)

沒有留言:

張貼留言