25

I am trying to send an SMTP email when certain values in database crosses its threshold value.

I have already allowed ports 25,587 and 465 in the Windows firewall and disabled the option of preventing mass mail in the Antivirus. The code I am using is given below

using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

 MailMessage mailMsg = new MailMessage();
        mailMsg.To.Add("[email protected]");
        // From
        MailAddress mailAddress = new MailAddress("[email protected]");
        mailMsg.From = mailAddress;


        // Subject and Body
        mailMsg.Subject = "MCAS Alert";
        mailMsg.Body = "Parameter out of range";


        SmtpClient smtpClient = new SmtpClient("smtp.servername.com", 25);
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Timeout = 30000;
        System.Net.NetworkCredential credentials =
           new System.Net.NetworkCredential("username", "passwrod");
        smtpClient.Credentials = credentials;
        smtpClient.EnableSsl = true;
        //ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
        smtpClient.Send(mailMsg);

Stack Trace

[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions xx.xx.xx.xx:25]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +208
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +464

[WebException: Unable to connect to the remote server]
   System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6) +6486360
   System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback) +307
   System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +19
   System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +324
   System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) +141
   System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint) +170
   System.Net.Mail.SmtpClient.GetConnection() +44
   System.Net.Mail.SmtpClient.Send(MailMessage message) +1554

[SmtpException: Failure sending mail.]
   System.Net.Mail.SmtpClient.Send(MailMessage message) +1906
   Admin_Alert.SMTPAuth() in c:\Users\spandya\Documents\Visual Studio 2012\WebSites\WebSite3\Admin\Alert.aspx.cs:61
   Admin_Alert.Page_Load(Object sender, EventArgs e) in c:\Users\spandya\Documents\Visual Studio 2012\WebSites\WebSite3\Admin\Alert.aspx.cs:22
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

What else I am missing here? Firewall inbound rules are there for these specific port addresses.

10
  • 1
    is the error coming from the sending machine or the receiving one? Commented Dec 31, 2013 at 10:42
  • Check the edit for Stack Trace
    – SPandya
    Commented Dec 31, 2013 at 10:47
  • Have you tried Telnetting to this port from the machine in question to ensure that the route is open? Something like telnet smtp.mydomain.com 25 Commented Dec 31, 2013 at 14:13
  • Mainly SocketException (0x271d) is thrown for port block, so can you check netstat -anb | find "25" on that server or telnet smtp.servername.com 25 from remote to check if that port is open on your smtp server?
    – Momin
    Commented Dec 31, 2013 at 21:46
  • I tried telnet but it said could not connect to the host on port 25
    – SPandya
    Commented Jan 1, 2014 at 4:42

7 Answers 7

23

Please confirm that your firewall is allowing outbound traffic and that you are not being blocked by antivirus software.

I received the same issue and the culprit was antivirus software.

3
  • I have allowed port 25 which I am targeting on both inbound and outbound of windows firewall.
    – SPandya
    Commented Jan 3, 2014 at 4:00
  • 1
    I disabled the antivirus and firewall both.
    – SPandya
    Commented Jan 3, 2014 at 4:02
  • Has the StackTrace of the exception changed? Commented Jan 3, 2014 at 5:04
14
+50

Ok, so very important to realize the implications here.

Docs say that SSL over 465 is NOT supported in SmtpClient.

Seems like you have no choice but to use STARTTLS which may not be supported by your mail host. You may have to use a different library if your host requires use of SSL over 465.

Quoted from http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.enablessl(v=vs.110).aspx

The SmtpClient class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information.

An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported.

4
  • Well the desired port that I am targeting is 25. And I am trying to send mail using the email in outlook not gmail.
    – SPandya
    Commented Jan 3, 2014 at 3:59
  • 1
    @SPandya You can't "send mail" using Outlook. Outlook is a mail client. You need an outbound SMTP gateway. In most cases (like for businesses) outlook is connecting to a Microsoft Exchange server which is the SMTP gateway that you would use. Many ISP's do not allow residential customers push SMTP mail (because of botnets and infected spam computers) Commented Jan 3, 2014 at 21:56
  • 1
    I am not sending it from Outlook. I am doing it from the SMTP Mail Server provided by the organization.
    – SPandya
    Commented Jan 4, 2014 at 4:52
  • @SPandya Either way, just make sure you understand the limitations of the SmtpClient class in regards to SSL. Commented Jan 6, 2014 at 21:40
13

I got this error:

System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

when the port was used by another program.

4

If the other answers don't work you can check if something else is using the port with netstat:

netstat -ano | findstr <your port number>

If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:

netsh interface ipv4 show excludedportrange protocol=tcp

1
  • Checking the excluded port range was the trick for me. No way of telling the default config for my app was using an excluded range, and the error doesn't indicate this in any way.
    – MDahlke
    Commented Apr 17, 2020 at 17:16
3

Windows Firewall was creating this error for me. SMTP was trying to post to GMAIL at port 587. Adding port 587 to the Outbound rule [Outbound HTTP/SMTP/RDP] resolved the issue.

1

I had a same issue. It was working fine on the local machine but it had issues on the server. I have changed the SMTP setting. It works fine for me.

If you're using GoDaddy Plesk Hosting, use the following SMTP details.

Host = relay-hosting.secureserver.net
Port = 25 
1
  • This was incredibly useful for fixing my email issue through Plesk. My local tests worked using Host smtpout.secureserver.com but kept throwing errors when the site was live on Plesk.
    – JDMX
    Commented Apr 1, 2020 at 16:46
0

Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.

Here is the code - The code is in asp.net core 2.0 but should work in above versions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;

namespace UnityAssets.Website.Services
{
    public class EmailSender : IEmailSender
    {
        public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
        {
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
            email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
            email.Subject = subject;

            var body = new BodyBuilder
            {
                HtmlBody = htmlMessage
            };

            email.Body = body.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //provider specific settings
                await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
                await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);

                await client.SendAsync(email).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.