2017-07-17 56 views
-2

我試圖用以下代碼從服務器發送帶有gmailaccount的郵件。c#gmail連接失敗,因爲連接的主機未能響應

  var fromAddress = new MailAddress("[email protected]", "xxxxxx"); 
     var toAddress = new MailAddress(toMailAddress); 
     const string fromPassword = "xxxxx"; 

     var smtp = new SmtpClient 
     { 
      Host = "smtp.gmail.com", 
      Port = 587, 
      EnableSsl = true, 
      DeliveryMethod = SmtpDeliveryMethod.Network, 
      UseDefaultCredentials = false, 
      Credentials = new NetworkCredential(fromAddress.Address, fromPassword) 
     }; 
     using (var message = new MailMessage(fromAddress, toAddress) 
     { 
      IsBodyHtml = true, 
      Subject = mailSubject, 
      Body = htmlBody 
     }) 
     { 
      smtp.Send(message); 
     } 

這讓我部署我的Windows服務器上,雖然我有一個Inobound規則在防火牆上的端口587的下一個結果。當我測試它的本地

connectionFailed

+1

看看這個問題也學會使用調試器來逐步通過您的代碼 - [使用C#發送郵件到Gmail帳戶](https://stackoverflow.com/questions/29251189/sending-mail-using -gmail-smtp-from-csharp-net) – MethodMan

+0

[使用C#通過Gmail SMTP服務器發送電子郵件的可能的副本](https://stackoverflow.com/questions/704636/sending-email-through-gmail-smtp-server-帶着-c-sharp) –

+0

根據OP對以下奇怪接受的答案的評論,我正在投票決定將其作爲本地化版本,因爲OPs託管公司在防火牆中開放了一個端口。 –

回答

-1

我也面臨這個問題,它的工作原理完美。實際上,Gmail不允許訪問Gmail,以便爲安全性較低的應用發送郵件。如果你得到像

"An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll 

Additional information: The SMTP server requires a secure connection or the 
client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at" 
  1. 轉到例外您的谷歌帳戶「我的帳戶」 : 執行以下步驟。
  2. 在「登錄&安全性」下面,您會發現「允許安全性較低的應用:關閉」,您需要點擊旁邊的按鈕將其打開。
  3. 現在您的Gmail帳戶將可從您的代碼訪問。
+0

可悲的是,這不是解決方案。 「允許不太安全的應用程序」已打開。如果關閉,我不認爲我在本地工作。 – Lieven

+0

請分享完整的例外,你會得到 –

+0

你會發現這裏的例外:https://i.stack.imgur.com/bBqff.png – Lieven

相關問題