从Console应用程序发送电子邮件时导致Socket异常的原因是什么?

时间:2012-10-02 14:17:14

标签: c# email smtpclient

我正在尝试编写一个会发送电子邮件的基本控制台应用。问题是我一直得到Socket异常:

  

尝试以访问权限xxx.xxx.x.xxx:25禁止的方式访问套接字

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

我在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, IPAddress& address, Socket& abortSocket, Socket& abortSocket
6, Int32 timeout)
   at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, 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

5 个答案:

答案 0 :(得分:17)

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

答案 1 :(得分:0)

端口25是否已启用且可用?例如,this thread解释了其他服务可以对其进行独占访问。

您是否在其他计算机上尝试过此代码(安全性较低)?我并不是说这是修复的一部分,而是为了确保代码本身是正常的。

答案 2 :(得分:0)

尝试使用EnableSsl。在msdn异常的原因:

  

EnableSsl设置为true,但SMTP邮件服务器未在对EHLO命令的响应中公布STARTTLS。

同时检查异常的StatusCode。

答案 3 :(得分:0)

要么不指定端口,要么不要使用EnableSSL = true。执行其中一项可以解决您的问题。

您正在尝试启动不允许以这种方式进行的通信。

答案 4 :(得分:0)

我更改为MailKit.Net.Smtp.SmtpClient。它提供了更好的错误,并且我能够使电子邮件正常工作。

using MimeKit;
using MailKit.Net.Smtp;
using System.Net;

using (var client = new SmtpClient())
    {
        client.Connect
            (
                Context.Settings.SMTPServer,
                Convert.ToInt32(Context.Settings.SMTPPort),
                MailKit.Security.SecureSocketOptions.None
            );

        //ignore ssl errors
        client.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

        // Note: only needed if the SMTP server requires authentication
        if (Context.Settings.SMTPAuthenticate)
        {

            client.Authenticate
                (
                        new NetworkCredential
                        (
                            Context.Settings.SMTPUserName,
                            Context.Settings.SMTPPassword,
                            Context.Settings.SMTPDomain
                        )
                );
        }


        await client.SendAsync(message);
        client.Disconnect(true);

        }