Cannot connect to remote server while sending mail - c#

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.

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

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.

Can't sent email exchange RPC HTTP

Ok so I tried in so many ways to sent this email but i just cannot get, this are the only two given by provider of the service
the url of the exchange Server
EXVMBX016-3.exch016.msoutlookonline.net
proxy to connect over http
dc016-8.exch016.msoutlookonline.net
NOTE: I tried with SSL
Now my problem it's that in the default port which i'm understand it's 25 the connection it's refused so i opened my outlook and with a sniffer i tried to see what's the port opened in that url, it was 135 give's a timeout.
System.Net.NetworkCredentialnetworkCredentials = new System.Net.NetworkCredential("example#example.com", "*****");
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("example#example.com");
message.Subject = "Esto es una prueba de direccion";
message.From = new System.Net.Mail.MailAddress("example#example.com");
message.Body = "Esto es una prueba del servicio de direcciones";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("EXVMBX016-3.exch016.msoutlookonline.net");
//smtp.Port = 135
//smtp.EnableSsl = False
smtp.UseDefaultCredentials = false;
smtp.Credentials = networkCredentials;
smtp.Send(message);
So If Do i miss something?. or What am I doing wrong?
UPDATE
Here's some images of my configuration on outlook
Your problem is that you are using wrong SMTP Address. Based on my understanding an Exchange Server name can not be SMTP name cEXVMBX016-3.exch016.msoutlookonline.net. Your SMTP Server Address will be different then what have you used above and that's why the connection is refused. When sending any email you just need correct SMTP address and proper credentials to connect it, that's it. I believe your code is correct.
To get correct SMTP address, open your email address contact card in Outlook and then look for "Email Address" properties and there you will get correct SMTP address and use in above code.
[Added Later after above images are added]
Based on above images, you are using Exchange Server Address as SMTP address which is wrong. You must get the correct SMTP address from your IT and then use that to send your email. Your code is right so correct SMPT address will work immediately.

Message submission rate for this client has exceeded the configured limit?

I have a for loop which calls some code sending emails. I get the following run-time error:
Service not available, closing transmission channel. The server
response was: 4.4.2 Message submission rate for this client has
exceeded the configured limit
After googling around it appears to be related to the "set-receiveconnector", possible for exchange server? Could anyone advise how I can fix this?
the code:
var mail = new MailMessage();
var smtpServer = new SmtpClient(SMTPServer);
mail.From = new MailAddress(fromAddress);
mail.To.Add(toAddress);
mail.Subject = title;
mail.IsBodyHtml = isHTML;
mail.Body = message;
if(attach != null) mail.Attachments.Add(attach);
smtpServer.Port = xxx
smtpServer.UseDefaultCredentials = false;
smtpServer.Credentials = new NetworkCredential(SMTPUser, SMTPPassword);
smtpServer.EnableSsl = true;
smtpServer.Send(mail); //Error occurs here
Rather then sending the emails directly can you use a pickup folder?
SmtpMail.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
that way you just dump the messages in to the folder and let exchange send them when its ready, this way if your user can only send say 3 per minute exchange should send 3 then on the next pass send another 3 and so on.
I resolved this problem on my system by using the correct port. The way exchange had been set up meant that SSL = TRUE, Port = 587 produced this error. If I changed it to use Port 25, then everything worked just fine. So check with your sys admins this may help!
We fixed this from the Exchange side by setting the receive connector(s) to allow more than 5 messages at a time, eg:
Get-ExchangeServer | Set-ReceiveConnector "My Receive Connector" -Messageratelimit 20

How to Send Email via Yandex SMTP (C# ASP.NET)

Formerly, I used my server as mail host and was sending emails via my own host. Now, I use Yandex as my mail server. I'm trying to send emails via Yandex SMTP. However, I could not achieve it. I get "the operation has timed out" message every time. I'm able to send & receive email with the same settings when I use Thunderbird. Hence, there is no issue with the account. I appreciate your guidance. You can see my code below:
EmailCredentials credentials = new EmailCredentials();
credentials.Domain = "domain.com";
credentials.SMTPUser = "email#domain.com";
credentials.SMTPPassword = "password";
int SmtpPort = 465;
string SmtpServer = "smtp.yandex.com";
System.Net.Mail.MailAddress sender = new System.Net.Mail.MailAddress(senderMail, senderName, System.Text.Encoding.UTF8);
System.Net.Mail.MailAddress recipient = new System.Net.Mail.MailAddress(recipientEmail, recipientName, System.Text.Encoding.UTF8);
System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage(sender, recipient);
email.BodyEncoding = System.Text.Encoding.UTF8;
email.SubjectEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(mailBody, #"<(.|\n)*?>", string.Empty), null, MediaTypeNames.Text.Plain);
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailBody, null, MediaTypeNames.Text.Html);
email.AlternateViews.Clear();
email.AlternateViews.Add(plainView);
email.AlternateViews.Add(htmlView);
email.Subject = mailTitle;
System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();
SMTP.Host = SmtpServer;
SMTP.Port = SmtpPort;
SMTP.EnableSsl = true;
SMTP.Credentials = new System.Net.NetworkCredential(credentials.SMTPUser, credentials.SMTPPassword);
SMTP.Send(email);
After so many trials & errors, I have found how to make it work. I have made the following changes on the code posted in the question:
Set SmtpPort = 587
Added the following 2 lines of code:
SMTP.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
SMTP.UseDefaultCredentials = false;
Additional note:
I use Azure server. I realized later that I did not configure the smtp endpoint for port 465. That being said, I had to add the 2 lines of code above in order to make email delivery work, just changing the port was not enough. My point is it is worth to check the defined ports on Azure and firewall before doing anything further.
I was able to make my code work by getting help from #Uwe and also #Dima-Babich, #Rail who posted on the following page Yandex smtp settings with ssl
. Hence, I think credits to answer this question should go to them.
Try using port 25 instead of 465 specified in Yandex help. I found this info on https://habrahabr.ru/post/237899/. They mentioned that it might be due to the fact that explicit SSL mode was implemented in the SmtpClient. Then port 25 is used for establishing connection in unencrypted mode and after that, protected mode is switched on.
I had the same problem.
I solved it by going to the Yandex mail, and then change some settings.
Go to:
1- Settings.
2- Email clients.
3- Set selected POP3 setting that is all.

Categories