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."
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.
I installed hmailserver 5.3.2 and configured it. It receives and sends
emails normally, but I wanted to use it to send emails from a .net/C#
application located in another server, and for that I wanted to use
SSL communication. Before, the application was configured to send
emails via gmail, on port 587 and it worked ok, but now we want to use
our own mail server. We first configured the application to connect on
smtp.domain.com on port 25 and that works, it sends the email.
Then we
created a self signed certificate to test the if we could send the
message through a secure channel.I created the certificate with
openSSL setting common name as: mail.domain.com, smtp.domain.com,
*.domain.com, domain.com. I opened port 587 on the firewall and
configured hmailserver to use a certificate for inbound connections on
that port.
None of the certificates I created worked (I tried one and then
created another one and so on), generating the following (generic) exception in the
application:
System.Exception: _COMPlusExceptionCode = -532459699
Of course I also tried to connect via telnet: telnet smtp.domain.com
587, and I just got a blank screen. It is not a firewall issue since
when I disable the ssl on port 587 I can connect normally.
Looking at the log doesn't even show an attempt to connect when using
587 with SSL.
I already checked these questions: Getting SmtpClient to work with a self signed SSL certificate and Using a self-signed certificate with .NET’s HttpWebRequest/Response, but it didn't solve my problem. The approach with ServerCertificateValidationCallback didn't have any influence.
I tried with ports 25 (which is also proposed in one of the questions above), 465, 587, and with all 3 it happens the same: The initial handshake (SYN / SYN-ACK / ACK) and after about 80s the connection is closed (FIN), nothing in between.
Do I have to install that certificate somewhere so the .net application sees it as trusted? I mean, I already installed it as a Trusted Root Certification Authority and could check by running mmc, so I have no idea where to go now...
Thanks for the help!
PS: Not sure if this belongs to ServerFault since it concerns a C# application but also a mail server...
EDIT: Code sample:
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
SmtpClient mailClient = new SmtpClient("smtp.domain.com");
mailClient.Credentials = new NetworkCredential("username#domain.com", "pwd");
mailClient.Port = 587;
mailClient.EnableSsl = true;
MailMessage mailMessage = new MailMessage("mailAddressFrom", "mailAddressTo", "subject", "body");
mailMessage.IsBodyHtml = true;
mailClient.Send(mailMessage);
EDIT 2: Log (Based on Ramunas' suggestion):
"TCPIP" 3588 "2010-06-23 10:02:49.685" "TCPConnection - Posting AcceptEx on 0.0.0.0:465"
"DEBUG" 3588 "2010-06-23 10:02:49.809" "Creating session 24039"
"TCPIP" 772 "2010-06-23 10:04:29.639" "TCPConnection - SSL handshake with client failed. Error code: 2, Message: End of file, Remote IP: X"
"DEBUG" 772 "2010-06-23 10:04:29.639" "Ending session 24039"
currently, you can not send mail using c# 4/.NET 4 to a hMailServer regardless whether the certificate used by hMailServer is purchased or self-signed.
the problem is two part AFAIK ... c# 4/.NET 4 will only send using TLS and port 587; hMailServer does not currently support STARTTLS. c# 4/.NET 4 does not support the alternative of 465/SSL.
see this thread "configuring SSL confusion ..." at hMailServer's forum.
"SmtpClient.EnableSsl Property ":
"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." -- MSDN
As gerryLowry said:
c# 4/.NET 4 will only send using TLS and port 587;
hMailServer does not currently support STARTTLS
You can update your hMailServer to hMailServer 5.5.1 (BETA) here
It now supports STARTTLS and with port 587 all is working correctly.
This is a sophisticated mechanism but in simple words client (computer you're making connection from) should know about WHO is certificate issuer (in your case your server is certificate issuer). If it does not find it in it's Trusted Root Certificate Authorities list then it considers this connection to be unsafe. (I bet you've seen browser warning you about unsafe request to some https://.... site).
Open Certificates snap-in in your Microsoft management console on a client computer and try to add the same self signed certificate to a Trusted Root Certificate Authorities list.
I installed hMailServer, created self signed certificate, added it to hMailServer and was not able to send mail via it, too. Though I was successful while sending emails without certificate.
I enabled logging on hMailServer (for everything) and tried again with no luck. But I saw an error in a log file stating
"Severity: 2 (High), Code: HM5113,
Source: TCPServer::Run(), Description:
Failed to load certificate file. Path:
<...>test.cer,
Address: 0.0.0.0, Port: 25, Error: An
invalid argument was supplied"
Maybe this is a case on your hMailServer also?
I have port 25 as normal SMTP open on my hMailServer as well as port 465 for SSL, so I had to change my code to point to the normal SMTP configuration. It should work after that. As for SSL, sorry, it won't work on hMailServer...
MailMessage message = new MailMessage();
message.From = new MailAddress("me#myself.home", "Me");
message.Body = "hello, World!";
message.To.Add(new MailAddress("you#myself.home", "You"));
SmtpClient client = new SmtpClient("secure.myself.home", 25);
client.EnableSsl = false;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("me#myself.home", "pwd");
client.Send(message);