Cannot access website from the same server - c#

I have a website on http://SomeDomain.com. when I go to that domain from any computer I am able to access the website. If I then go to that same domain but from the server that is hosting that website I will not be able to access the site. It looks like if a firewall will not be enabling the connection.
I know I can go to http://localhost from within that server in order to access the website.
Anyways the problem is that I cannot send emails from that server I have the following code to send an email:
public static void SendEmail(string toEmailAddress, string subject, string body)
{
var fromAddress = new MailAddress("sales#domainName.com", "domainName");
var toAddress = new MailAddress(toEmailAddress);
string fromPassword = "MY_PASSWORD";
var smtp = new SmtpClient
{
Host = "mail.toglcloud.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("v040\\sales.domainName", fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(message);
}
}
when I run that code from any computer (I already tried 5 different ones) it works! But if I run that exact code on the server (computer hosting website and that contains mail server) it does not work. I get the following exception:
System.Net.Mail.SmtpException: Failure sending mail. --->
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: A connection attempt failed
because the connected party did not properly respond after a period of
time, or established connection failed because connected host has
failed to respond 206.155.112.15:587 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 ---
I think it has to do with the same reason why I cannot find the endpoint http://SomeDomain.com

The difference between 5 other computers and the server:
1. Which user are you logged in as? What are permissions for the user.
2. Firewall permissions (biggest chance since the mail server is totally not accessible)
3. For the website - is it IE permissions (often on the server this could be an issue)

For me, I added an entry in the host file and it works well.

Related

MailKit: The handshake failed due to an unexpected packet format

I got exception when I try to connect to my SMTP server using MailKit SmtpClient. BUT my mails have been sent successfully if I use System.Net.Mail.SmtpClient with the same parameters!
The exception message: An error occurred while attempting to establish an SSL or TLS connection.
The inner exception message: The handshake failed due to an unexpected packet format.
Questions
Why does MailKit.Net.Smtp.SmtpClient throw exception but System.Net.Mail.SmtpClient doesn't? What is the difference between them?
How to fix it?
Code
Initialize the parameters required for mail sending:
var host = "myhost.com";
var port = 2525;
var from = "from#mydomain.com";
var to = "to#mydomain.com";
var username = "from#mydomain.com";
var password = "myPassword";
var enableSsl = true;
Sending mail using System.Net.Mail.SmtpClient:
var client = new System.Net.Mail.SmtpClient
{
Host = host,
Port = port,
EnableSsl = enableSsl,
Credentials = new NetworkCredential(username, password)
};
client.Send(from, to, "subject", "body"); // success.
But when I try to connect to the host using MailKit with the same host and port, I got the exception:
var mailKitClient = new MailKit.Net.Smtp.SmtpClient();
mailKitClient.Connect(host, port, enableSsl); // it throws the exception.
The problem is that you are connecting to a plain-text port and expecting SSL.
In MailKit, the true/false useSsl parameter is used to decide whether or not to connect in SSL mode or plain-text mode.
In System.Net.Mail, they don't support connecting in SSL mode, they only support upgrading a plain-text connection to SSL mode using the STARTTLS command once the connection has been established.
To overcome this, MailKit has a different Connect() method that takes an enum value SecureSocketOptions.
What you want is SecureSocketOptions.StartTls:
var mailKitClient = new MailKit.Net.Smtp.SmtpClient();
mailKitClient.Connect(host, port, SecureSOcketOptions.StartTls);

how to solve socket connection error for bulk mails on private domains?

{"A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond 72.167.238.32:25"}
public bool IsExists_SMTPMethod(string email)[socket connection error screenshot][1]
{
string domain = email.Substring(email.IndexOf("#") + 1);
var servers = _commander.GetMXServers(domain);
Socket socket = null;
foreach (MXServer mxserver in servers)
{
IPHostEntry ipHost = Dns.Resolve(mxserver.MailExchanger);
IPEndPoint endPoint = new IPEndPoint(ipHost.AddressList[0], 25);
socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(endPoint);
if (!CheckResponse(socket, ResponseEnum.ConnectSuccess))
{
socket.Close();
}
else
{
// If connected, send SMTP commands
{
SendData(socket, string.Format("HELO {0}\r\n", "machinename"));
if (!CheckResponse(socket, ResponseEnum.GenericSuccess))
{
socket.Close();
continue;
}
SendData(socket, string.Format("MAIL FROM: <{0}>\r\n", "from#domain.com"));
CheckResponse(socket, ResponseEnum.GenericSuccess);
SendData(socket, string.Format("RCPT TO: <{0}>\r\n", email));
bool result = CheckResponse(socket, ResponseEnum.GenericSuccess);
if (!result)
{
socket.Close();
continue;
}
else
return true;
}
}
}
return false;
}
Unless you know the SMTP server accept unauthenticated connections on port 25, your code is very limitative but should work for a private SMTP Server. Nevertheless even you host your own SMTP Server, but attempt to deliver an email message on a realiable internet address, the recipient's SMTP server may reject the incoming email because your SMTP server is considered untrusted.
Please review the following configuration of the SMTP Server you attempt to target:
does the SMTP server accept only client IP Address explictly registered? Even on private domains this is often the case.
is SMTP on 25 allowed ? or do i need to use SMTP SSL / SMTP TLS ?
is SMTP server allow anonymous connections? On Internet to avoid spam this is no more the case. Even on private domains authentication may be required.
if you use your own SMTP Server but attempt to deliver messages to public email addresses, is your server correctly setup to send email messages over Internet? (MX, Reverse DNS, SPF ...)
There may be a lot of reason for an SMTP server to reject the connection. But if this is on a private domain, review your SMTP Server configuration or ask your SMTP Server administrator required parameters.

Cannot connect to remote server while sending mail

I'm using code below to send an email and it just doesn't work and gives an exception:
MailDefinition md = new MailDefinition();
md.IsBodyHtml = true;
md.From = EMAIL_FROM;
md.Subject = "لینک تغییر رمز";
MailMessage mm = md.CreateMailMessage(to, null, new System.Web.UI.Control());
string body = link;
mm.Body = body;
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false;
smtp.Host = EMAIL_SMTP;
smtp.Port = EMAIL_PORT;
smtp.Credentials = new System.Net.NetworkCredential(EMAIL_FROM, EMAIL_PASSWORD);
smtp.Send(mm);
where sender username & password are checked and correct, port is 25 and smtp is mail.kawp.co.ir, on send function it throws an exception with the below error message
{"Unable to connect to the remote server"}
{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xx.xxx.xx.xx:25"}
I'm using the same method and function for my other domains which are hosted on the same server and they are working fine. What possibly could be causing the problem here?
p.s: I also can't handshake with the mail.kawp.co.ir 25 via telnet
Thanks in advance
Changing port 25 to 587 fixed my problem because my isp is blocking port 25 to prevent spamming.
If you cannot perform the handshake with Telnet, then you're not going to get it to connect programmatically. From what it sounds like, the server isn't configured to accept SMTP messages. You'll need to get that enabled before you can get your code to work.

Mailbox unavailable. The server response was: relay not permitted

I am sending emails via an external SMTP server. Sending the email is handled with this code:
try
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.From = new MailAddress(froma);
mail.To.Add(toc);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
SmtpClient smtp = new SmtpClient(ClientServer);
DataSet ds = new DataSet();
int retCode = Email.getSmtp(ref ds, DatabaseName);
string User="";
string Password="";
if (ds.Tables["Value"].Rows.Count > 0)
{
User = ds.Tables["Value"].Rows[0]["UserName"].ToString();
Password = ds.Tables["Value"].Rows[0]["PasswordName"].ToString();
}
else
{
MessageBox.Show("Invalid SMTP settings!");
return;
}
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(User, Password);
smtp.EnableSsl = false;
smtp.Send(mail);
}
catch (System.Web.HttpException exHttp)
{
System.Console.WriteLine("Exception occurred:" + exHttp.Message);
}
Testing this code on my server, with my own SMTP server on the same network, this returns all my emails. However, using an external SMTP server causes the error:
Mailbox unavailable. The server response was: relay not permitted.
I have read around and it appears that the admin for SMTP must allow relays for my server. However, using the authentication credentials provided, I can't seem to connect, and am still receiving the relay error.
Yes, it sounds like the external server that you are using is not allow relay. Even if you have the proper authentication credentials, you will not be able to send the email because the relay function is still disabled. Are you the admin of this external server? If you are then you can enable it. This LINK HERE explains how to set up SMTP and the relay. If you are not the admin of this external server, then you will have to contact who is so they can enable the SMTP and relay for you.
It sounds like the server on your network has SMTP installed and the relay is set up properly since you are able to send. I had to install SMTP and configure the relay on all three of servers here (development box, staging box, and production box) to send emails. I hope this information helps.
I had the same error and commented out :
//smtp.UseDefaultCredentials = true;
And the email was sent successfully.

C# SMTP virtual server doesn't send mail

C# SMTP virtual server doesn't send mail. Here's the code:
public static void SendEmail(string _FromEmail, string _ToEmail, string _Subject, string _EmailBody)
{
// setup email header .
SmtpMail.SmtpServer = "127.0.0.1";
MailMessage _MailMessage = new MailMessage();
_MailMessage.From = _FromEmail;
_MailMessage.To = _ToEmail;
_MailMessage.Subject = _Subject;
_MailMessage.Body = _EmailBody;
try
{
SmtpMail.Send(_MailMessage);
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
String str = ex.InnerException.ToString();
}
}
It is an Interop exception because that .NET code is relying on Interop(erability) services, non-managed stuff. The message however is pretty clear, the server is unable to relay because it has been configured to reject relaying of emails.
Many years ago that was not a problem and you could virtually use any public SMTP server to send emails. With the advent of SPAM the whole game changed, now in most servers relaying is disabled and your mail send request is rejected.
What you will need here so that it does not reject your mail, is to authenticate your request (account/user and password on that server). It has to be a valid username & password combination known to that SMTP server. You do that by setting those (out of my head sorry) in the .Credentials property. See also the UseDefaultCredentials property, if you set Credentials you need to make sure UseDefaultCredentials is false.
If the error is this:
550 5.7.1 Unable to relay for ragaei.mahmoud#invensys.com
Then your SMTP server cannot send to that email address. Use a different SMTP server or configure it to relay out to the internet. The local one will probably only send to addresses on your own domain. If this is an SMTP server configuration question, you may have more luck asking on Superuser.

Categories