2015-07-22 464 views
5

我試圖通過SmtpClient連接到iCloudMailkit SMTP - 啓動TLS和TLS標誌

我使用的設置如下:

服務器名稱:smtp.mail.me.com
要求SSL :是
如果您在使用SSL時看到錯誤消息,請嘗試使用TLS或STARTTLS。
端口:587
SMTP需要身份驗證:是 - 與相關用戶名和密碼

如果我使用SSL我得到「握手失敗,原因是意外的數據包格式」

如果我不使用SSL視覺工作室調試器掛在連接上。

我認爲問題是我不告訴SmtpClient使用tls,但我無法找到如何做到這一點的文檔。

的代碼如下:

using (var client = new SmtpClient()) { 
    client.Timeout = 1000 * 20; 
    //client.Capabilities. 
    client.AuthenticationMechanisms.Remove ("XOAUTH2"); 

    client.Connect("SMTP.mail.me.com", 587, false); //dies here 
    //client.Connect(servername, port, useSsl); 
    //can I set tls or starttls here?? 
    client.Authenticate(username, password); 
    client.Send(FormatOptions.Default, message); 
} 

我能夠手動設置TLS或啓動TLS。我嘗試過的一件事是以下,但它似乎並沒有工作

client.Connect(new Uri("smtp://" + servername + ":" + port + "/?starttls=true")); 

感謝您的任何幫助。

+0

如果你說你需要'SSL',你爲什麼要爲'useSSL'標誌傳遞'false'? – Rob

+0

@Rob我已經嘗試使用true,並且由於意外的數據包格式而導致握手失敗。 iCloud建議:「如果您在使用SSL時看到錯誤消息,請嘗試使用TLS或STARTTLS。」 – cavej03

回答

8

您正在使用的Connect()方法僅允許啓用/禁用與StartTLS不同的SSL封裝連接。

由於混亂,我已經實現了一個單獨的Connect()方法,使這更明顯的是怎麼回事:

using (var client = new SmtpClient()) { 
    // Note: don't set a timeout unless you REALLY know what you are doing. 
    //client.Timeout = 1000 * 20; 

    // Removing this here won't do anything because the AuthenticationMechanisms 
    // do not get populated until the client connects to the server. 
    //client.AuthenticationMechanisms.Remove ("XOAUTH2"); 

    client.Connect ("smtp.mail.me.com", 587, SecureSocketOptions.StartTls); 

    client.AuthenticationMechanisms.Remove ("XOAUTH2"); 

    client.Authenticate (username, password); 
    client.Send (message); 
} 

嘗試。

+0

這個工程.. @ cavej03請接受這個安裝程序 – om471987

0

您可以設置選項爲 「SecureSocketOptions.Auto」 像這樣

await client.ConnectAsync(mailService.Host, mailService.Port, SecureSocketOptions.Auto); 

MailKit會自動決定使用SSL或TLS。

+0

它有什麼用途來決定?端口號? –

+0

您必須在模型中設置的端口號。這只是谷歌郵件的端口號或任何。所以我只是打電話給我的模型,並從我的DB請求端口和主機....但是這裏重要的是「SecureSocketOptions.Auto」 – error505

+0

@PaulKnopf是的,MailKit使用端口來決定。這不是世界上最好的系統,但它在99%的時間內工作。 – jstedfast