我認爲,如果你正在尋找測試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");
}
,但不是真的,有可能是一個原因捕獲異常等原因...而且我知道這個具體的可能性,並且想要處理它,因爲它是自己的情況......這有道理嗎? – adeena 2008-12-16 21:18:35
我試圖實現交易電子郵件發件人和例外不能使用,因爲測試應該在事務流的不同部分。 – 2015-03-09 12:39:29