Office 365 SMTP starts firing net_io_connectionclosed - c#

A while ago I've configured my ASP.NET C# project to send e-mail via Office 365, but last week it's starting to throw a lot of exceptions.
System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
How can I prevent this from happening?
MailMessage message = new MailMessage(System.Configuration.ConfigurationManager.AppSettings["smtpfrom"], email, strOnderwerp, strBody);
message.Priority = MailPriority.Normal;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["smtpserver"], Convert.ToInt32((System.Configuration.ConfigurationManager.AppSettings["smtpport"])));
client.EnableSsl = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["smtpssl"]); ;
client.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["smtpuser"], System.Configuration.ConfigurationManager.AppSettings["smtppass"]);
client.Send(message);
client.Dispose();
The exceptions seems to be thrown on the Dispose.

In our case, we were already using smtp.office365.com endpoint, yet all of a sudden we started receiving net_io_connectionclosed on one of our machines, while same code was working perfectly on others. Investigation shown that those machines resolved smtp.office365.com to different IP addresses, and it looked like one of the servers was misbehaving.
On attemt to write support inquiry, it appeared that Microsoft is playing bad trick on us:
Recently, we started rejecting a percentage of connections to
smtp.office365.com that uses TLS1.0/1.1 for SMTP AUTH (complete
disablement will start early 2022).
And that was just it. Switching to TLS 1.2 fixed whole thing.

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
this worked for me

This same issue started at my company on February 8th. The problem would come and go with no pattern.
What I believe solved the problem was a change to the SMTP server address.
Our original SMTP server address was podxxxxx.outlook.com and still works most of the time. I checked for the current O365 SMTP server address in our portal and it should be smtp.office365.com.
I changed my config to point to this new address and the problem seems to have gone away. My logs show no errors for the last 24+ hours after the change.
If the error starts happening again I will update this.

If you all face this issue in 2022, that might be the case of Microsoft decided to stop supporting TLS1.0, TLS1.1 for service endpoint "smtp.office365.com".
To resolve it,
Either use "smtp-legacy.office365.com"
or
Configure client to use TLS1.2 by
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Read this article from Microsoft Tech Community for more details

The holy grail of all this bothering with the net_io_connectionclosed Errors while connecting to Office365 in VB.NET or c# is the TSL Version.
When you are working with a VB.NET oder c# Application wanting to connect, send an receive Msg. to/from O365 you have to force TLS12 in you code.
Just put the last line below your EnableSSL = True an you will be fine:
Last Line to force TLS12

Related

Unable to send mail from C# App using godaddy details

Despite spending an entire morning with GoDaddy chat, and reading almost everything I can find on sending emails via godaddy I am still no closer to solving my issue.
What Have I tried
Firstly, this is my code.
var smtpClient = new SmtpClient("smtpout.secureserver.net")
// var smtpClient = new SmtpClient("relay-hosting.secureserver.net", 25)
{
Port = 25,
UseDefaultCredentials = false,
EnableSsl = false,
Credentials = new NetworkCredential("user#User.com", "Password#"),
// DeliveryMethod = SmtpDeliveryMethod.Network,
};
and I think I should mention that this works when I attempt to use google's free smpt server, the mail is sent. However using my godaddy credentials, I get the following error,
Message = "Service not available, closing transmission channel. The server response was: Cannot connect to SMTP server 72.167.234.197 (72.167.234.197:25), connect error 10060" other times it says
InnerException = {"Unable to read data from the transport connection: An established connection was aborted by the software in your host machine."}
I have also tried other suggested ports like 587 , 80, 3552. Nothing has changed, I have also tried the suggestion at this link https://www.godaddy.com/help/send-email-using-systemnetmail-19291 . Which did not work (no suprise to me, cause where am i putting the account password) . Would appreciate it if anyone has solved getting their C# application to work with Godaddy. Like I said it works with Google so I dont believe my code is an issue in anyway.
regards
Your code looks good, however, one way to test if you are using the correct smtp settings is to send the email with a program like Microsoft Outlook or Thunderbird. Also, if you are using a dedicated server or a VPS, you need to use
dedrelay.secureserver.net
See: https://in.godaddy.com/help/what-is-my-servers-email-relay-server-16601
Also, check out this see: https://in.godaddy.com/community/VPS-Dedicated-Servers/Unable-to-send-email-from-C-net-application-from-website/m-p/102913#M1256
which mentions: "If you are using a Plesk shared hosting plan, use relay-hosting.secureserver.net and port 25. Do not specify a username or password. Other relay/smtp servers will not work from our shared hosting."

Get SSL error SSL_ERROR_RX_RECORD_TOO_LONG in server side

I have written my own webserver in C#.
And I always established SSL certificates for my sites in new IP on port 443. And always it works fine.
But this time I get this error:
Secure Connection Failed
An error occurred during a connection to www.sayehrooshan-co.com. SSL received a record that exceeded the maximum permissible length. Error code:
SSL_ERROR_RX_RECORD_TOO_LONG
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
Please contact the website owners to inform them of this problem.
this is page address:
https://www.sayehrooshan-co.com
this is my code always worked with .pfx file for other sites:
sslstream = new SslStream(new NetworkStream(mySocket, false), false);
//commented for nedaye arzhang
X509Certificate2 serverCertificate = new X509Certificate2(Path, Password);
//X509Certificate2 serverCertificate = new X509Certificate2("www_nedaye-arzhang_com.cer");
sslstream.AuthenticateAsServer(serverCertificate, false, System.Security.Authentication.SslProtocols.Tls, true);
searched alot but didn't get any solution
Anyone get any idea?
The server is broken. Trying with openssl s_client shows that the TLS handshake is done successfully and the certificate is fine, but that it breaks later in the communication:
$ openssl s_client -connect www.sayehrooshan-co.com:443 -servername www.sayehrooshan-co.com -crlf
CONNECTED(00000003)
...
SSL-Session:
Protocol : TLSv1
Cipher : ECDHE-RSA-AES256-SHA
...
Verify return code: 0 (ok)
---
GET / HTTP/1.1
Host: www.sayehrooshan-co.com
140040623380160:error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number:s3_pkt.c:365:
Doing a packet capture during the experiment one can see that the server sends plain text on the TLS connection:
> various TLS encrypted stuff from client (likely HTTP request) ....
< followed by sudden plain text from the server:
Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
at MyWebServerNamespace.MyWebServer.SetTableRowValue(DataSet& ds, String type, String name, String value) in D:\iteration source - table 13 removed\MyWebServer\MyWebServer.cs:line 4024
at MyWebServerNamespace.MyWebServer.LoadCmsValues(Content cms, Ssl sslClass, DataSet& Ds, DataTable& fileDt, Socket& mySocket, Byte[]& contentBytes, Boolean& showCmsError) in D:\iteration source - table 13 removed\MyWebServer\MyWebServer.cs:line 1761
at MyWebServerNamespace.MyWebServer.HandleTcpRequest(Object state) in D:\iteration source - table 13 removed\MyWebServer\MyWebServer.cs:line 1027
LoadCmsValues enter
The client will try to interpret this plain text message as a TLS record. This means it will parse the initial bytes and extract the TLS protocol version and payload length. Given that this is no TLS record at all these values will be garbage. Depending on the actual implementation of the TLS stack in the client this will then result in error messages like "wrong version number" (the claimed TLS protocol version is not supported) or "SSL_ERROR_RX_RECORD_TOO_LONG" (the length of the payload as specified is not the actual length of the payload) or the more general "ERR_SSL_PROTOCOL_ERROR" or similar.
It is not just C#, Firefox shows the same error message.
"Error code: ssl_error_rx_record_too_long. This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate."
Source
Another page discussing this issue
Firefox:
Chrome
IE
Grasshopper has same problem possibly because of two routers and dns bind being installed on one ip address and ssl mod the other. The fact that Apache2 status is up and running like a charm tells me that it’s an install/ops error. Tomorrow is another day.

SendGrid Unable to read data from the transport connection: net_io_connectionclosed

I am getting an exception thrown sending an email via SendGrid since recently upgrading a project to .net 4.5.2
Failure sending mail. System.IO.IOException: Unable to read data from
the transport connection: net_io_connectionclosed. at
System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer,
Int32 offset, Int32 read, Boolean readLine) at
System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader
caller, Boolean oneLine) at
System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader
caller) at System.Net.Mail.CheckCommand.Send(SmtpConnection conn,
String& response) at
System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command,
MailAddress from, Boolean allowUnicode) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,
MailAddressCollection recipients, String deliveryNotify, Boolean
allowUnicode, SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message) at
System.Net.Mail.SmtpClient.Send(MailMessage message) at
SendGridMail.Transport.SMTP.SmtpWrapper.Send(MailMessage mime) at
SendGridMail.Transport.SMTP.Deliver(ISendGrid message) at
ReACT.Classes.Business.Helpers.Email.Send(String[] to, String[]
toNames, Boolean ccToSender, String[] ccTo, String[] ccToNames, String
subject, String body, Boolean isHtml, String SMTPServer, String
EmailUserName, String EmailPassword, String EmailPort, String
SystemEmailAddress, String SystemEmailName, String& FriendlyException,
String& TechnicalException)
The code used to send the email via SMTP using the SendGrid service is as follows -
SendGridMail.SendGrid vEmailMessage = SendGridMail.SendGrid.GetInstance(vMailMessage.From, vMailMessage.To.ToArray(), vMailMessage.CC.ToArray(), new MailAddress[0], vMailMessage.Subject, vMailMessage.Body, vMailMessage.Body);
NetworkCredential vCredentials = new NetworkCredential(this.ApplicationSettings.EmailUserName, this.ApplicationSettings.EmailPassword);
var vTransport = SMTP.GetInstance(vCredentials);
//Send email message
vTransport.Deliver(vEmailMessage);
The credentials are correct and confirmed as working correctly. This problem has only started since the .net framework upgrade and unfortunately, we cannot downgrade back to target .net 4
I had the same problem. I had the wrong username. I thought this was the ApiKey that I created for this, I even tried the email with and without domain. The solution was that the SMTP username is "apikey", as in that exact string, not your apikey, not the internal identifier nor the 'friendly' name you gave it. Just the exact 6 letters of "apikey".
For those experiencing the same exception when sending emails via SendGrid, it turned out that a new piece of functionality was passing an incorrect password to the SendGrid API resulting in a AuthenticationFailedException: 535 Authentication failed: Bad username / password.
I discovered this after downloading Wireshark, finding & inspecting the SendGrid packets to find the data sent to the API was incorrect under a certain condition. The SendGrid API then returned a rather helpful AuthenticationFailedException exception however when this exception was caught in a try catch block in code, the actual exception was masked and came out as the aforementioned net_io_connectionclosed IOException
I fixed the bug in our new application and the issue went away. If only the actual exception being thrown by the SendGrid API was the one caught in the try catch block!
const string username="apikey";
string pass = "xxxxxxxxxxxxxxxxxxxxx" // login sendgrid.com => create ApiKey
NetworkCredential vCredentials = new NetworkCredential("apikey", pass);
I have followed this guide
Link: https://sendgrid.com/docs/API_Reference/SMTP_API/integrating_with_the_smtp_api.html
I had the same issue, but it had to do with enabling 2FA in my sendgrid account before upgrading my SMTP and API V3 code to Key-based authentication.
If you enable 2FA before doing the other stuff, it breaks authentication.
For us - this non-descript error was due to reaching the sending limits for our sendgrid email api subscription. I would recommend checking your sendgrid account first before messing about with website settings.
I did notice that a service was sending a lot of messages and using all the 25.000/month messages available in the azure free account plain.
To solve the problem, I created a new account and fixed the service to send a lower number of messages.
I had the same error but it was because I had included a domain parameter in the NetworkCredential
In our case this was a network issue. We had to enable the company's firewall to allow web socket connections from our service to SendGrid/Twilio as the new C# client we had to switch to (SendGridClient) uses sockets. Previously we used the C# generic MailClient which used SMTP/HTTP.

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

I am using the SmtpClient library to send emails using the following:
SmtpClient client = new SmtpClient();
client.Host = "hostname";
client.Port = 465;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User", "Pass);
client.Send("from#hostname", "to#hostname", "Subject", "Body");
The code works fine in my test environment, but when I use production SMTP servers, the code fails with an SmtpException "Failure sending mail." with an inner IOException "Unable to read data from the transport connection: net_io_connectionclosed".
I've confirmed that firewalls are not an issue. The port opens just fine between the client and the server. I'm not sure what else could throw this error.
EDIT: Super Redux Version
Try port 587 instead of 465. Port 465 is technically deprecated.
After a bunch of packet sniffing I figured it out. First, here's the short answer:
The .NET SmtpClient only supports encryption via STARTTLS. If the EnableSsl flag is set, the server must respond to EHLO with a STARTTLS, otherwise it will throw an exception. See the MSDN documentation for more details.
Second, a quick SMTP history lesson for those who stumble upon this problem in the future:
Back in the day, when services wanted to also offer encryption they were assigned a different port number, and on that port number they immediately initiated an SSL connection. As time went on they realized it was silly to waste two port numbers for one service and they devised a way for services to allow plaintext and encryption on the same port using STARTTLS. Communication would start using plaintext, then use the STARTTLS command to upgrade to an encrypted connection. STARTTLS became the standard for SMTP encryption. Unfortunately, as it always happens when a new standard is implemented, there is a hodgepodge of compatibility with all the clients and servers out there.
In my case, my user was trying to connect the software to a server that was forcing an immediate SSL connection, which is the legacy method that is not supported by Microsoft in .NET.
Putting this at the beginning of my method fixed this for me
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12
For anyone who stumbles across this post looking for a solution and you've set up SMTP sendgrid via Azure.
The username is not the username you set up when you've created the sendgrid object in azure. To find your username;
Click on your sendgrid object in azure and click manage. You will be redirected to the SendGrid site.
Confirm your email and then copy down the username displayed there.. it's an automatically generated username.
Add the username from SendGrid into your SMTP settings in the web.config file.
Hope this helps!
Change port from 465 to 587 and it will work.
I've tried all the answers above but still get this error with Office 365 account. The code seems to work fine with Google account and smtp.gmail.com when allowing less secure apps.
Any other suggestions that I could try?
Here is the code that I'm using
int port = 587;
string host = "smtp.office365.com";
string username = "smtp.out#mail.com";
string password = "password";
string mailFrom = "noreply#mail.com";
string mailTo = "to#mail.com";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
using (SmtpClient client = new SmtpClient())
{
MailAddress from = new MailAddress(mailFrom);
MailMessage message = new MailMessage
{
From = from
};
message.To.Add(mailTo);
message.Subject = mailTitle;
message.Body = mailMessage;
message.IsBodyHtml = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = host;
client.Port = port;
client.EnableSsl = true;
client.Credentials = new NetworkCredential
{
UserName = username,
Password = password
};
client.Send(message);
}
UPDATE AND HOW I SOLVED IT:
Solved problem by changing Smtp Client to Mailkit. The System.Net.Mail Smtp Client is now not recommended to use by Microsoft because of security issues and you should instead be using MailKit. Using Mailkit gave me clearer error messages that I could understand finding the root cause of the problem (license issue). You can get Mailkit by downloading it as a Nuget Package.
Read documentation about Smtp Client for more information:
https://learn.microsoft.com/es-es/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=netframework-4.7.2
Here is how I implemented SmtpClient with MailKit
int port = 587;
string host = "smtp.office365.com";
string username = "smtp.out#mail.com";
string password = "password";
string mailFrom = "noreply#mail.com";
string mailTo = "mailto#mail.com";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(mailFrom));
message.To.Add(new MailboxAddress(mailTo));
message.Subject = mailTitle;
message.Body = new TextPart("plain") { Text = mailMessage };
using (var client = new SmtpClient())
{
client.Connect(host , port, SecureSocketOptions.StartTls);
client.Authenticate(username, password);
client.Send(message);
client.Disconnect(true);
}
You may also have to change the "less secure apps" setting on your Gmail account. EnableSsl, use port 587 and enable "less secure apps". If you google the less secure apps part there are google help pages that will link you right to the page for your account. That was my problem but everything is working now thanks to all the answers above.
Answer Specific to Outlook Mailer
var SmtpClient = new SmtpClient{
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential("email", "password"),
Port = 587,
Host = "smtp.office365.com",
EnableSsl = true }
https://admin.exchange.microsoft.com/#/settings
-> Click on Mail Flow
-> Check - Turn on use of legacy TLS clients
-> Save
removing
client.UseDefaultCredentials = false;
seemed to solve it for me.
Does your SMTP library supports encrypted connection ? The mail server might be expecting secure TLS connection and hence closing the connection in absence of a TLS handshake
If you are using an SMTP server on the same box and your SMTP is bound to an IP address instead of "Any Assigned" it may fail because it is trying to use an IP address (like 127.0.0.1) that SMTP is not currently working on.
To elevate what jocull mentioned in a comment, I was doing everything mention in this thread and striking out... because mine was in a loop to be run over and over; after the first time through the loop, it would sometimes fail. Always worked the first time through the loop.
To be clear: the loop includes the creation of SmtpClient, and then doing .Send with the right data. The SmtpClient was created inside a try/catch block, to catch errors and to be sure the object got destroyed before the bottom of the loop.
In my case, the solution was to make sure that SmtpClient was disposed after each time in the loop (either via using() statement or by doing a manual dispose). Even if the SmtpClient object is being implicitly destroyed in the loop, .NET appears to be leaving stuff lying around to conflict with the next attempt.
Change your port number to 587 from 465
I got the same problem with the .NET smtp client + office 365 mail server: sometimes mails were sent successfully, sometimes not (intermittent sending failures).
The problem was fixed by setting the desired TLS version to 1.2 only. The original code (which started to fail in the middle of the year 2021 - BTW) was allowing TLS 1.0, TLS 1.1 and TLS 1.2.
Code (CLI/C++)
int tls12 = 3072; // Tls12 is not defined in the SecurityProtocolType enum in CLI/C++ / ToolsVersion="4.0"
System::Net::ServicePointManager::SecurityProtocol = (SecurityProtocolType) tls12;
(note: the problem was reproduced and fixed on a Win 8.1 machine)
First Use Port = 587
Generally STARTTLS is required to send mail, Adding the Security Protocol Tls12 will help to resolve this issue.
Secondly test the stmp connection using powershell
$userName = 'username_here'
$password = 'xxxxxxxxx'
$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $pwdSecureString
$sendMailParams = #{
From = 'abc.com'
To = 'xyz#gmail.com'
Subject = 'Test SMTP'
Body = 'Test SMTP'
SMTPServer = 'smtp.server.com'
Port = 587
UseSsl = $true
Credential = $credential
}
Send-MailMessage #sendMailParams
Thirdly If this send out the email, Add below code inside SmtpClient function:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Since Jan 22 2022, Google has increased the TLS version requirements Also Microsoft has revoked the support for TLS 1.0 and TLS 1.1 for the earlier versions of the .NET framework than 4.6.
So we can fix the issue one of the below 2 solutions.
1.By Adding some other Protocols before creating the smtp client >> ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
2.You just need to update the .NET framework version to 4.6 or higher to fix the issue.
In my case, the customer forgot to add new IP address in their SMTP settings. Open IIS 6.0 in the server which sets up the smtp, right click Smtp virtual server, choose Properties, Access tab, click Connections, add IP address of the new server. Then click Relay, also add IP address of the new server. This solved my issue.
If your mail server is Gmail (smtp.google.com), you will get this error when you hit the message limit. Gmail allows sending over SMTP up to only 2000 messages per 24 hours.
I ran into this when using smtp.office365.com, using port 587 with SSL. I was able to log in to the account using portal.office.com and I could confirm the account had a license. But when I fired the code to send emails, I kept getting the net_io_connectionclosed error.
Took me some time to figure it out, but the Exchange admin found the culprit. We're using O365 but the Exchange server was in a hybrid environment. Although the account we were trying to use was synced to Azure AD and had a valid O365 license, for some reason the mailbox was still residing on the hybrid Exchange server - not Exchange online. After the exchange admin used the "Move-Mailbox" command to move the mailbox from the hybrid exchange server to O365 we could use the code to send emails using o365.
If you are using Sendgrid and if you receive this error, it is because Basic authentication is no more allowed by sendgrid.We need to create API key and use them as NetworkCredential. username="apikey" password will be your API key
Reference - https://docs.sendgrid.com/for-developers/sending-email/integrating-with-the-smtp-api
I recently had to set new mail settings on all our applications and encountered this error on multiple projects.
The solution for me was to update the target framework to a newer version on some of my projects.
I also had an ASP.net website project where updating the target framework wasn't enough I also had to add the following code to the web.config <httpRuntime targetFramework="4.8"/>
After trying all sorts of TLS/SSL/port/etc things, for me the issue was this: the username and password I was using for Credentials were not correct, apparently.
Normally our websites use a different set of credentials but this one's were different. I had assumed they were correct but apparently not.
So I'd double check my credentials if nothing else is working for you. What a precise error message!
Try this : Here is the code which i'm using to send emails to multiple user.
public string gmail_send()
{
using (MailMessage mailMessage =
new MailMessage(new MailAddress(toemail),
new MailAddress(toemail)))
{
mailMessage.Body = body;
mailMessage.Subject = subject;
try
{
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Credentials =
new System.Net.NetworkCredential(email, password);
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
mail = new MailMessage();
String[] addr = toemail.Split(','); // toemail is a string which contains many email address separated by comma
mail.From = new MailAddress(email);
Byte i;
for (i = 0; i < addr.Length; i++)
mail.To.Add(addr[i]);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
mail.DeliveryNotificationOptions =
DeliveryNotificationOptions.OnFailure;
// mail.ReplyTo = new MailAddress(toemail);
mail.ReplyToList.Add(toemail);
SmtpServer.Send(mail);
return "Mail Sent";
}
catch (Exception ex)
{
string exp = ex.ToString();
return "Mail Not Sent ... and ther error is " + exp;
}
}
}
In case if all above solutions don't work for you then try to update following file to your server (by publish i mean, and a build before that would be helpful).
bin-> projectname.dll
After updating you will see this error.
as i have solved with this solution.
For outlook use following setting that is not giving error to me
SMTP server name smtp-mail.outlook.com
SMTP port 587
This error is very generic .It can be due to many reason such as
The mail server is incorrect.
Some hosting company uses mail.domainname format.
If you just use domain name it will not work.
check credentials
host name
username password if needed
Check with hosting company.
<smtp from="info#india.uu.com">
<!-- Uncomment to specify SMTP settings -->
<network host="domain.com" port="25" password="Jin#" userName="info#india.xx.com"/>
</smtp>
</mailSettings>
In my case the web server IP was blocked on the mail server, it needs to be unblocked by your hosting company and make it whitelisted. Also, use port port 587.
My original problem is about intermittent sending failures. E.g. First Send() succeeds, 2nd Send() fails, 3rd Send() succeeds. Initially I thought I wasn't disposing properly. So I resorted to using().
Anyways, later I added the UseDefaultCredentials = false, and the Send() finally became stable.
Not sure why though.
SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
There are two solutions. First solution is for app level (deployment required) and second one is for machine level (especially if you use an out-of-the-box / off-the-shelf app)
When we checked the exception, we saw that the protocol is "ssl|tls" depriciated pair.
Since we don't want to deploy, we prefer machine level change (Solution 2).
On August 18, Microsoft announced that they will disable Transport Layer Security (TLS) 1.0 and 1.1 connections to Exchange Online “in 2022.”
https://office365itpros.com/2021/08/19/exchange-online-to-introduce-legacy-smtp-endpoint-in-2022/
Firstly let's check the network (Anything prevents your email sent request? firewall, IDS, etc.)
By using PowerShell check Transport Layer Security protocols
[Net.ServicePointManager]::SecurityProtocol
My Output: Tls, Tls11, Tls12
Test SMTP Authentication over TLS
$HostName = [System.Net.DNS]::GetHostByName($Null).HostName
$Message = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("smtp.office365.com", 587)
$smtp.Credentials = New-Object System.Net.NetworkCredential("me#me.com", "PassMeme");
$smtp.EnableSsl = $true
$smtp.Timeout = 400000
$Message.From = "sender#me.com"
$Message.Subject = $HostName + " PowerShell Email Test"
$Message.Body = "Email Body Message"
$Message.To.Add("receiver#me.com")
#$Message.Attachments.Add("C:\foo\attach.txt")
$smtp.Send($Message)
My output:
There is no error message
If there is any message on your output something prevents your email sent request.
If everything is ok there should be two solutions.
Solution 1:
Application Level TLS 1.2 Configuration (Optional)
Application deployment required.
Explicitly choose TLS in C# or VB code:
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12
Solution 2:
Machine level TLS 1.2 .NET Framework configuration
Application deployment NOT required.
Set the SchUseStrongCrypto registry setting to DWORD:00000001. You should restart the server.
For 32-bit applications on 32-bit systems or 64-bit applications on 64-bit systems), update the following subkey value:
HKEY_LOCAL_MACHINE\SOFTWARE\
\Microsoft\.NETFramework\\<version>
SchUseStrongCrypto = (DWORD): 00000001
For 32-bit applications that are running on x64-based systems, update the following subkey value:
HKEY_LOCAL_MACHINE\SOFTWARE\
Wow6432Node\Microsoft\\.NETFramework\\<version>
SchUseStrongCrypto = (DWORD): 00000001
For details "How to enable TLS 1.2 on clients" on
https://learn.microsoft.com/en-us/mem/configmgr/core/plan-design/security/enable-tls-1-2-client
Our email service is Azure SendGrid.
Our application stopped sending emails one day, and the error message was "SmtpException: Unable to receive data from the transport connection: net io connectionclosed." We discovered the problem was caused by the fact that our Pro 300K subscription had run out. Emails began to be sent when we upped our subscription.
I was facing the same issue with my .NET application.
ISSUE: The .NET version that I was using is 4.0 which was creating the whole mess.
REASON: The whole reason behind the issue is that Microsoft has revoked the support for TLS 1.0 and TLS 1.1 for the earlier versions of the .NET framework than 4.6.
FIX: You just need to update the .NET framework version to 4.6 or higher to fix the issue.

"Unable to read data from the transport connection: net_io_connectionclosed." - Windows Vista Business and SMTP

Unable to test sending email from .NET code in Windows Vista Business.
I am writing code which I will migrate to an SSIS Package once it its proven. The code is to send an error message via email to a list of recipients.
The code is below, however I am getting an exception when I execute the code.
I created a simple class to do the mailing... the design could be better, I am testing functionality before implementing more robust functionality, methods, etc.
namespace LabDemos
{
class Program
{
static void Main(string[] args)
{
Mailer m = new Mailer();
m.test();
}
}
}
namespace LabDemos
{
class MyMailer
{
List<string> _to = new List<string>();
List<string> _cc = new List<string>();
List<string> _bcc = new List<string>();
String _msgFrom = "";
String _msgSubject = "";
String _msgBody = "";
public void test(){
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me#domain.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "this is a sample body";
mail.IsBodyHtml = false;
//send the message
SmtpClient smtp = new SmtpClient();
smtp.Host = "emailservername";
smtp.Port = 25;
smtp.UseDefaultCredentials = true;
smtp.Send(mail);
}
}
Exception Message
Inner Exception
{"Unable to read data from the transport connection: net_io_connectionclosed."}
Stack Trace
" at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)\r\n at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)\r\n at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)\r\n at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)\r\n at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)\r\n at System.Net.Mail.SmtpClient.GetConnection()\r\n at System.Net.Mail.SmtpClient.Send(MailMessage message)"
Outer Exception
System.Net.Mail.SmtpException was unhandled
Message="Failure sending mail."
Source="System"
StackTrace:
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at LabDemos.Mailer.test() in C:\Users\username\Documents\Visual Studio 2008\Projects\LabDemos\LabDemos\Mailer.cs:line 40
at LabDemos.Program.Main(String[] args) in C:\Users\username\Documents\Visual Studio 2008\Projects\LabDemos\LabDemos\Program.cs:line 48
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.IO.IOException
Message="Unable to read data from the transport connection: net_io_connectionclosed."
Source="System"
StackTrace:
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
InnerException:
There are several things that can cause this problem, and here are some of the things that I've found.
Questions: You mention "Exchange" -- Is this an exchange server? Does the host require authentication (maybe you need to add authentication to the client)? What I would try doing first is assigning the host to the static IP address instead of the host name to see if that works first. If it does then it's most likely a problem with the DNS mapping.
If you are running your exchange server with Virtualization, you need to configure the SmtpClient to the host IP of the Virtual Server, not the physical hosting server name or IP. Right click on Default SMTP virtual server, select Properties, then go to Access tab, click Relay then add the IP address of the computer that send SMTP request to the SMTP server. (ASP.net site)
If this doesn't work, it's because the server is blocking you from sending SMTP packets. You need to make sure to add the box you are sending the SMTP messages from to the SMTP server. This is done through IIS's authentication tab.
I would also like to point out that you should dispose the mail client, or use the client in a "using" statement. This will make sure that the "QUIT" is sent to the server and gracefully close the connection.
using(SmtpClient smtp = new SmtpClient())
{
smtp.Host = "emailservername";
smtp.Port = 25;
smtp.UseDefaultCredentials = true;
smtp.Send(mail)
}
Restart IIS. I know this sounds silly, to do a restart for everything. (and sorry to bump up an old thread). But sometimes restarting IIS works magic. I faced the exact same issue and restarting solved it.
Might have happened cause temporarily the name 'localhost' couldn't be resolved. I;m just posting here so that someone who faces it now will probably try this quick fix before attempting to investigate further. Hope it helps
If you've specified an IP address in the SMTP Service settings then make sure you're specifying that IP address of the machine within IIS7 and not putting localhost.
IIS7 makes it easy to select 'localhost' but that will lead to this error if the IP for instance is 10.0.0.1
If you are using localhost (Use Localhost) in IIS 7, then change it to IP address of the machine instead of localhost or 127.0.0.1
Also follow below link to update your mail server relay accordingly:
Mailbox unavailable. The server response was: 5.7.1 Unable to relay for abc#xyz.com
Vista and Windows 7 does not have any SMTP server, this facility has been removed since Windows XP, so you need to setup your SMTP server explicitly, several tools are available in market for that, you can check that out.
Also once you configure the SMTP, remember to check the server name which you would be using to send the e-mail.
I had the same issue since I had multiple IP on my server (Virtual Servers) and my host was pointing to localhost while my SMTP Virtual Server was assigned to one particular IP:
<smtp deliveryMethod="Network">
<network host="localhost" port="25" defaultCredentials="false"/>
</smtp>
There are 2 solutions for this:
Change your code and set host to the particular IP that is being used by SMTP Virtual Server instead of localhost.
Change SMTP Virtual Server IP to All Unassigned
To see/change SMTP Virtual Server IP:
Right click on Default SMTP virtual server, select Properties, on General tab change/see IP address.
Hope this saves someone's day with the same issue.
I have found that the Vista Business OS does not come with IIS SMTP. I suspect this is the missing piece of the puzzle. Has anyone had any luck with this issue?
Is your code incompleted.Dash is correct in identifying it.Other then that check smtp component is installed or not
check link text
I am facing this issue last 6hr and I am new on that so I am trying to solve this issue in following way
1) I opened command prompt (e.g. Ctrl + R type cmd and enter).
2) And check to SMTP server ping and check response.
3) If it’s gets response then it’s ok and to move next step 4 other wise smtp name is wrong.
4) Then I check by telnet smtp port (e.g. 25 ) is open or not.
5) Using this cmd we check the SMTP response.
6) telnet "yoursmtpname" "portno” (e.g. telnet smtp.gmail.com 25)
7) If telnet is not working, please install or add from control panel in add new features.
8) If it’s working then it’s pass result like.
9) 220 mx.google.com ESMTP .
Using above steps we can find out smtp connection is ready or not to sending mail.
I developed a Windows Service application in VB using .NET Framework v4.5 and recently ran into this issue.
First, a little background - I ran into the OP's error after trying to deal with the error "Service not available, closing transmission channel. The server response was: Error: too many messages in one session" which was resolved by calling the Dispose method on the SmtpClient object after each email sent. Just to be ultra safe, I also called Dispose on the MailMessage object.
Okay, so now the 'too many messages in one session' issue is resolved but now I occasionally got the 'Unable to read data from the transport connection: net_io_connectionclosed' error. Awesome. Turns out I had not implemented my email class consistently - in one instance, it was being disposed of while in the other it was not.
Here's an example of what resolved both issues for me (it's in VB but you get the idea):
With New clsEmail(True)
With .Message
.To.Add("user#domain.com")
.Subject = msgSubject
.Body = msgContents
End With
.Server.Send(.Message)
.Server.Dispose()
.Message.Dispose()
End With
My email class has, among other things, has 2 properties - Message (System.Net.Mail.MailMessage) and Server (System.Net.Mail.SmtpClient) which is what's being disposed in this example.
I haven't had a single problem after hundreds of emails once every single instance that sends email in my service was implemented in this way.
upgrade to .NET 4.0 and apply all security updates
I was facing the same issue for one month. I tried all the possible solutions provided on Microsoft's official site. Finally, I found the root cause of it.
I have updated targetFramework from 4.5.2 to 4.6.1 in web.config file.
compilation debug="true" targetFramework="4.6.1"
httpRuntime maxRequestLength="183500800" executionTimeout="3600" targetFramework="4.6.1" enableVersionHeader="false"
the above solution worked for me, and now my emails are triggering successfully from the application.

Categories