1. 程式人生 > 實用技巧 >.net 使用MimeKit與MailKit傳送郵件出現 An error occurred while attempting to establish an SSL or TLS connection.(轉)

.net 使用MimeKit與MailKit傳送郵件出現 An error occurred while attempting to establish an SSL or TLS connection.(轉)

現象

服務正式上線半年多,無錯誤。突然有一天發現傳送郵件失敗,日誌系統打印出日誌如下:

郵件傳送失敗:An error occurred while attempting to establish an SSL or TLS connection.

The SSL certificate presented by the server is not trusted by the system for one or more of the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server's certificate.
3. The certificate presented by the server is expired or invalid.

See https://github.com/jstedfast/MailKit/blob/master/FAQ.md#InvalidSslCertificate for possible solutions.

原因

檢視官方FAQ https://github.com/jstedfast/MailKit/blob/master/FAQ.md

發現我使用的是25埠,是一個標準純文字埠(這些埠根本不支援任何SSL / TLS加密),我去看我的程式碼也沒有使用ssl,感覺我的程式碼沒有什麼問題,而且已經在線上正常使用半年了;
根據現象明顯確定是Connect 方法報錯,然後去看官方文件
http://www.mimekit.net/docs/html/M_MailKit_MailService_Connect_3.htm

官方文件 該方法後面提示:

useSsl引數僅控制客戶端是否進行ssl包裝的連線。換句話說,即使useSsl引數為false,如果郵件伺服器支援STARTTLS擴充套件,仍然可以使用SSL/TLS。
若要禁用所有SSL/TLS的使用,請使用帶有SecureSocketOptions值的Connect(String、Int32、SecureSocketOptions、CancellationToken)過載。

原因找到了,郵件伺服器開啟了ssl支援,我使用的這個方法,usesll=false,任然去使用ssl/tls。而25埠不支援ssl/tls,所以連線不上;最後使用Connect(String、Int32、SecureSocketOptions、CancellationToken)過載就可以了