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

前端 未结 5 2050
走了就别回头了
走了就别回头了 2021-01-17 17:41

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 acc

相关标签:
5条回答
  • 2021-01-17 18:14

    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.

    0 讨论(0)
  • 2021-01-17 18:17

    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);
    
            }
    
    0 讨论(0)
  • 2021-01-17 18:20

    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

    0 讨论(0)
  • 2021-01-17 18:26

    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.

    0 讨论(0)
  • 2021-01-17 18:34

    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.

    0 讨论(0)
提交回复
热议问题