c# – 从控制台应用程序发送电子邮件时是什么原因导致套接字异常?

前端之家收集整理的这篇文章主要介绍了c# – 从控制台应用程序发送电子邮件时是什么原因导致套接字异常?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个基本的控制台应用程序,它将发送一封电子邮件.问题是我不断得到Socket异常:

An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.x.xxx:25

我关掉了我的Windows防火墙,但没有改变任何东西.我试图运行它没有指定的凭据.我也尝试使用不同的smtp服务器,包括smtp.mail.yahoo.com与端口25和我的凭据,但没有运气.导致此异常的问题是什么?

我在Windows 7上运行VS2008.下面是我的代码示例和我得到的异常.

  1. static void Main(string[] args)
  2. {
  3. String recipient = "recipient@email.com";
  4. String sender = "sender@email.com";
  5.  
  6. MailMessage message = new MailMessage();
  7. message.From = new MailAddress(sender);
  8. message.To.Add(new MailAddress(recipient));
  9. message.Subject = "Subject";
  10. message.Body = "Body";
  11.  
  12. SmtpClient smtp = new SmtpClient
  13. {
  14. Host = "smtp.server",Port = 25,EnableSsl = true,DeliveryMethod = SmtpDeliveryMethod.Network,//UseDefaultCredentials = false,//Credentials = new NetworkCredential("validemail","validpassword"),Timeout = 3000
  15. };
  16.  
  17. try
  18. {
  19. smtp.Send(message);
  20. }
  21. catch (Exception e)
  22. {
  23. Console.WriteLine(e.ToString());
  24. }
  25. }

而我得到的例外:

  1. System.Net.Mail.SmtpException: Failure sending mail. --->
  2. System.Net.WebException: Unable to connect to the remote server --->
  3. System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.x.xxx:25
  4. at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,SocketAddress socketAddress)
  5. at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,Socket s4,Socket s6,Socket& socket,IPAddress& address,ConnectSocketState state,IAsyncResult asyncResult,Int32 timeout,Exception& exception)
  6. --- End of inner exception stack trace ---
  7. at System.Net.ServicePoint.GetConnection(PooledStream PooledStream,Object owner,Boolean async,Socket& abortSocket,Socket& abortSocket
  8. 6,Int32 timeout)
  9. at System.Net.PooledStream.Activate(Object owningObject,GeneralAsyncDelegate asyncCallback)
  10. at System.Net.PooledStream.Activate(Object owningObject,GeneralAsyncDelegate asyncCallback)
  11. at System.Net.ConnectionPool.GetConnection(Object owningObject,GeneralAsyncDelegate asyncCallback,Int32 creationTimeout)
  12. at System.Net.Mail.SmtpConnection.GetConnection(String host,Int32 port)
  13. at System.Net.Mail.SmtpClient.Send(MailMessage message)
  14. --- End of inner exception stack trace ---
  15. at System.Net.Mail.SmtpClient.Send(MailMessage message)
  16. at ...Program.Main(String[] args) in ...\Program.cs:line xxx

解决方法

我有一个非常相似的情况,事实证明,防病毒只是阻止该端口.您可能的选项列在这里:
http://social.msdn.microsoft.com/Forums/br/transactsql/thread/c083c2c6-f74e-42cd-a811-4329ff7aa5f1

猜你在找的C#相关文章