2008-12-16 32 views
19

這與我前幾天詢問how to send email的問題有關。我可以在調用client.Send()之前測試SmtpClient嗎?

我的新的,相關的問題是這樣的......如果我的應用程序的用戶在防火牆或其他一些原因,行client.Send(郵件)將無法正常工作背後...

後行:

SmtpClient client = new SmtpClient("mysmtpserver.com", myportID); 
client.Credentials = new System.Net.NetworkCredential("myusername.com", "mypassword"); 

有我能做些事情來測試客戶端之前,我嘗試發送?

我想過把這個在一個try/catch循環,但我寧願做一個測試,然後彈出一個對話框說法:不能訪問SMTP或類似的東西。

(我假定,無論是我,也不是我的潛在應用程序的用戶,必須調整他們的防火牆設置的能力。比如......他們安裝工作中的應用,並沒有控制自己的上網工作)

-Adeena

回答

9

我認爲這是其中異常處理將是優選的解決方案的情況。你真的不知道它會工作,直到你嘗試,失敗是一個例外。

編輯:

您將要處理SmtpException。這有一個StatusCode屬性,它是一個枚舉,它會告訴你爲什麼Send()失敗。

+0

,但不是真的,有可能是一個原因捕獲異常等原因...而且我知道這個具體的可能性,並且想要處理它,因爲它是自己的情況......這有道理嗎? – adeena 2008-12-16 21:18:35

+0

我試圖實現交易電子郵件發件人和例外不能使用,因爲測試應該在事務流的不同部分。 – 2015-03-09 12:39:29

1

你可以嘗試發送HELO命令來測試服務器是否活躍,運行前發送電子郵件。 如果您想檢查用戶是否存在,您可以嘗試使用VRFY命令,但由於安全原因,這通常會在SMTP服務器上禁用。 延伸閱讀: http://the-welters.com/professional/smtp.html 希望這會有所幫助。

2

趕上SmtpException例外,它會告訴你,如果它失敗了,因爲你無法連接到服務器。

如果你想檢查是否可以打開任何嘗試,使用的TcpClient和捕捉SocketExceptions之前到服務器的連接。雖然我沒有看到這樣做的好處,但只是從Smtp.Send發現問題。

+0

恩,因爲它可能是你的應用程序的負載,或者你需要在輪詢的基礎上驗證與你的SMTP服務器的連接性,並且你還沒有發送電子郵件,並且你想測試/確保你的發送能力,當你這樣做 - 這就是爲什麼。 – vapcguy 2017-05-04 22:08:53

36

我認爲,如果你正在尋找測試SMTP那就是你正在尋找一種方式來驗證您的配置和網絡可用性,而無需實際發送電子郵件。任何方式,這是我所需要的,因爲沒有虛假的電子郵件,是有道理的。

在我的開發人員的建議下,我提出了這個解決方案。一個小幫手類,其用法如下。我在發送電子郵件的服務的OnStart事件中使用它。

注意:TCP套接字的功勞歸功於Peter A.布朗伯格在http://www.eggheadcafe.com/articles/20030316.asp和配置閱讀的東西在這裏的傢伙:Access system.net settings from app.config programmatically in C#

助手:

public static class SmtpHelper 
{ 
    /// <summary> 
    /// test the smtp connection by sending a HELO command 
    /// </summary> 
    /// <param name="config"></param> 
    /// <returns></returns> 
    public static bool TestConnection(Configuration config) 
    { 
     MailSettingsSectionGroup mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; 
     if (mailSettings == null) 
     { 
      throw new ConfigurationErrorsException("The system.net/mailSettings configuration section group could not be read."); 
     } 
     return TestConnection(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port); 
    } 

    /// <summary> 
    /// test the smtp connection by sending a HELO command 
    /// </summary> 
    /// <param name="smtpServerAddress"></param> 
    /// <param name="port"></param> 
    public static bool TestConnection(string smtpServerAddress, int port) 
    { 
     IPHostEntry hostEntry = Dns.GetHostEntry(smtpServerAddress); 
     IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port); 
     using (Socket tcpSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) 
     { 
      //try to connect and test the rsponse for code 220 = success 
      tcpSocket.Connect(endPoint); 
      if (!CheckResponse(tcpSocket, 220)) 
      { 
       return false; 
      } 

      // send HELO and test the response for code 250 = proper response 
      SendData(tcpSocket, string.Format("HELO {0}\r\n", Dns.GetHostName())); 
      if (!CheckResponse(tcpSocket, 250)) 
      { 
       return false; 
      } 

      // if we got here it's that we can connect to the smtp server 
      return true; 
     } 
    } 

    private static void SendData(Socket socket, string data) 
    { 
     byte[] dataArray = Encoding.ASCII.GetBytes(data); 
     socket.Send(dataArray, 0, dataArray.Length, SocketFlags.None); 
    } 

    private static bool CheckResponse(Socket socket, int expectedCode) 
    { 
     while (socket.Available == 0) 
     { 
      System.Threading.Thread.Sleep(100); 
     } 
     byte[] responseArray = new byte[1024]; 
     socket.Receive(responseArray, 0, socket.Available, SocketFlags.None); 
     string responseData = Encoding.ASCII.GetString(responseArray); 
     int responseCode = Convert.ToInt32(responseData.Substring(0, 3)); 
     if (responseCode == expectedCode) 
     { 
      return true; 
     } 
     return false; 
    } 
} 

用法:

if (!SmtpHelper.TestConnection(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None))) 
{ 
    throw new ApplicationException("The smtp connection test failed"); 
} 
-1

我也有這方面的需要。

Here's the library I made(它發送一個HELO並檢查了200,220或250):

using SMTPConnectionTest; 

if (SMTPConnection.Ok("myhost", 25)) 
{ 
    // Ready to go 
} 

if (SMTPConnectionTester.Ok()) // Reads settings from <smtp> in .config 
{ 
    // Ready to go 
} 
-1
private bool isValidSMTP(string hostName) 
    { 
     bool hostAvailable= false; 
     try 
     { 
      TcpClient smtpTestClient = new TcpClient(); 
      smtpTestClient.Connect(hostName, 25); 
      if (smtpTestClient.Connected)//connection is established 
      { 
       NetworkStream netStream = smtpTestClient.GetStream(); 
       StreamReader sReader = new StreamReader(netStream); 
       if (sReader.ReadLine().Contains("220"))//host is available for communication 
       { 
        hostAvailable= true; 
       } 
       smtpTestClient.Close(); 
      } 
     } 
     catch 
     { 
      //some action like writing to error log 
     } 
     return hostAvailable; 
    } 
相關問題