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.下面是我的代码示例和我得到的异常.

static void Main(string[] args)
{
        String recipient = "recipient@email.com";
        String sender = "sender@email.com";

        MailMessage message = new MailMessage();
        message.From = new MailAddress(sender);
        message.To.Add(new MailAddress(recipient));
        message.Subject = "Subject";
        message.Body = "Body";

        SmtpClient smtp = new SmtpClient
        {
            Host = "smtp.server",Port = 25,EnableSsl = true,DeliveryMethod = SmtpDeliveryMethod.Network,//UseDefaultCredentials = false,//Credentials = new NetworkCredential("validemail","validpassword"),Timeout = 3000
        };

        try
        {
            smtp.Send(message);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

而我得到的例外:

System.Net.Mail.SmtpException: Failure sending mail. ---> 
System.Net.WebException: Unable to connect to the remote server --->
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
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,SocketAddress socketAddress)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,Socket s4,Socket s6,Socket& socket,IPAddress& address,ConnectSocketState state,IAsyncResult asyncResult,Int32 timeout,Exception& exception)
   --- End of inner exception stack trace ---
   at System.Net.ServicePoint.GetConnection(PooledStream PooledStream,Object owner,Boolean async,Socket& abortSocket,Socket& abortSocket
6,Int32 timeout)
   at System.Net.PooledStream.Activate(Object owningObject,GeneralAsyncDelegate asyncCallback)
   at System.Net.PooledStream.Activate(Object owningObject,GeneralAsyncDelegate asyncCallback)
   at System.Net.ConnectionPool.GetConnection(Object owningObject,GeneralAsyncDelegate asyncCallback,Int32 creationTimeout)
   at System.Net.Mail.SmtpConnection.GetConnection(String host,Int32 port)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at ...Program.Main(String[] args) in ...\Program.cs:line xxx

解决方法

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

猜你在找的C#相关文章