2014-04-09 92 views
-1

發送電子郵件我有這樣的代碼片段發送一封電子郵件,但我每次EXCUTE它的時候,我得到這個例外通過谷歌

等待操作期限屆滿

public static void CreateTimeoutTestMessage(string server) 
    { 
     string to = "[email protected]"; 
     string from = "[email protected]"; 
     string subject = "Using the new SMTP client."; 
     string body = @"Using this new feature, you can send an e-mail message from an application very easily."; 
     MailMessage message = new MailMessage(from, to, subject, body); 
     SmtpClient client = new SmtpClient(server, 587); 
     client.EnableSsl = true; 
     client.Credentials=new NetworkCredential("[email protected]", "XXXXXXXXX"); 
     Console.WriteLine("Changing time out from {0} to 100.", client.Timeout); 
     client.Timeout = 100; 
     // Credentials are necessary if the server requires the client 
     // to authenticate before it will send e-mail on the client's behalf. 
     //client.Credentials = CredentialCache.DefaultNetworkCredentials; 

     try 
     { 
      client.Send(message); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Exception caught in CreateTimeoutTestMessage(): {0}", 
        ex.ToString()); 
     } 

     Console.ReadLine(); 
    } 
+6

提示:您正嘗試通過Gmail的SMTP服務器發送郵件,而不提供您嘗試發送的帳戶的憑據。您還沒有爲GMail的SMTP服務器(它的'587' IIRC)指定正確的端口..您應該在這裏查看類似的問題以獲得您需要的答案。 –

+0

請閱讀手冊:https://support.google.com/mail/answer/78775?hl=zh-CN –

+0

我添加了帳戶和gmail端口的憑據,但仍然收到相同的錯誤。 –

回答

0

當然你獲得超時 - 您爲超時指定了100毫秒。這很短。聯繫服務器併發送郵件可能需要超過100ms。嘗試一下10000ms十秒。

我知道它在您複製並粘貼的MSDN sample中,但它太短。這是最好的刪除下列行:

Console.WriteLine("Changing time out from {0} to 100.", client.Timeout); 
client.Timeout = 100; 

請試試這個(從here上心):

... 
    MailMessage message = new MailMessage(from, to, subject, body); 
    SmtpClient client = new SmtpClient(server, 587); 
    client.EnableSsl = true; 
    client.UseDefaultCredentials = false; // <--- NEW 
    client.Credentials = new NetworkCredential("[email protected]", "XXXXXXXXX"); 

這可能等待身份驗證。

+0

仍然無法正常工作..請任何其他幫助 –

+0

那麼它現在等待100秒(這是'超時'的默認值)? –

+0

是的,它等待100秒 –

0

如果您有:

SmtpClient client = new SmtpClient(server, 587); 

把它分解成:

SmtpClient client = new SmtpClient(); 
client.Host = "smtp.gmail.com"; 
client.Port = 587; 

因爲我沒有看到你所定義的服務器,如果你想使用Gmail,你可以只要宣佈它是這樣的主機,看看這是否讓你更接近你的目標。

另外一個方面,Gmail的SMTP不允許你改變發送地址,以防止網絡釣魚,所以如果你打算允許輸入改變變量,它不會工作,Gmail默認爲電子郵件在證書中提供

+0

當我的CreateTimeoutTestMessage函數我設置字符串server =「smtp.gmail .com「 我看不出將客戶分成兩部分的用處。 –

+0

就像我說的我沒有看到服務器的定義,所以我必須確保主機實際上正在設置。 –