这与我前几天询问如何发送电子邮件的问题有关.
我的新相关问题就是这个...如果我的应用程序的用户是在防火墙后面或者为什么行client.Send(mail)将无法工作...
线后:
SmtpClient client = new SmtpClient("mysmtpserver.com", myportID); client.Credentials = new System.Net.NetworkCredential("myusername.com", "mypassword");
在尝试发送之前,我可以做些什么来测试客户端?
我想把它放在try/catch循环中,但我宁愿做一个测试,然后弹出一个对话框说:无法访问smtp或类似的东西.
(我假设我和我的应用程序用户都没有能力调整他们的防火墙设置.例如......他们在工作时安装应用程序并且无法控制他们的互联网工作)
-Adeena
我认为,如果您要测试SMTP,那么您正在寻找一种方法来验证您的配置和网络可用性,而无需实际发送电子邮件.任何方式都是我需要的,因为没有任何虚拟的电子邮件是有意义的.
在我的开发人员的建议下,我提出了这个解决方案.一个小助手类,用法如下.我在发送电子邮件的服务的OnStart事件中使用它.
注意:TCP套接字的功劳归功于Peter A. Bromberg,网址为http://www.eggheadcafe.com/articles/20030316.asp,配置读取内容的人员:从app.config访问system.net设置以编程方式在C#中
帮手:
public static class SmtpHelper { ////// test the smtp connection by sending a HELO command /// /// ///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); } /// /// test the smtp connection by sending a HELO command /// /// /// 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"); }
我认为这是一种异常处理将是首选解决方案的情况.在你尝试之前,你真的不知道它会起作用,而失败是一个例外.
编辑:
你会想要处理SmtpException.它有一个StatusCode属性,它是一个枚举,它将告诉你Send()失败的原因.