What caused the Socket Exception while sending email from Console application?
Asked Answered
O

5

10

I'm trying to write a basic console app that will send an email. The problem is that I keep getting the Socket exception:

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

I turned off my windows firewall but it didn't change anything. I tried to run it with and without credentials specified. I also tried to use different smtp servers including smtp.mail.yahoo.com with port 25 and my credentials but with no luck. What is the problem causing this exception?

I'm running VS2008 on Windows 7. Below is my code sample and the exception I get.

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

        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());
        }
    }

And the exception I got:

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
Omen answered 2/10, 2012 at 14:17 Comment(0)
R
17

I had very similar situation once and it turned out that the antivirus was just blocking that port. Your possible options are listed here: http://social.msdn.microsoft.com/Forums/br/transactsql/thread/c083c2c6-f74e-42cd-a811-4329ff7aa5f1

Rangefinder answered 3/10, 2012 at 11:57 Comment(0)
M
0

Is port 25 enabled and available? For example this thread explains that is is possible for another service to have exclusive access to it.

Have you tried this code in another machine (with less security)? I don't mean that as part of a fix, but just to make sure that the code is OK by itself.

Mcclure answered 2/10, 2012 at 14:29 Comment(1)
I've checked that nothing is listening on that port. Once I test it on another machine I update the comment but I need to get home first to have another test machine.Omen
L
0

Try to play with EnableSsl. In msdn reason of exception:

EnableSsl is set to true, but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command.

Also check StatusCode of the exception.

Lamothe answered 2/10, 2012 at 14:49 Comment(1)
the status code is 10013. I've checked the meaning but I don't know how to solve the issue.Omen
S
0

Either don't assign the port or don't use EnableSSL = true. Doing one of this will solve your problem.

You are trying to initiate a communication which is not allowed to be done this way.

Stall answered 2/10, 2012 at 14:59 Comment(3)
I've tried all possible combinations and nothing has changed, still the same exception.Omen
EnableSSL needs to be set to false, otherwise there is a problem with authentication. On one machine, Avast warned me that SSL should be disabled, on the other I've just got Authentication Exception.Omen
I assume that the certificate on your mail server is expired. There is a workaround for that, let me know if it is really so.Stall
G
0

I changed to MailKit.Net.Smtp.SmtpClient. It gave better errors and I was able to get the emails to work.

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);

        }
Grosswardein answered 3/9, 2020 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.