Ever since I posted a quick guide to sending email via Mailkit in .NET Core 2, I have been inundated with comments and emails asking about specific exception messages that either Mailkit or the underlying .NET Core. Rather than replying to each individual email, I would try and collate all the errors with sending emails here. It won’t be pretty to read, but hopefully if you’ve landed here from a search engine, this post will be able to resolve your issue.
I should also note that the solution to our “errors” is usually going to be a change in the way we use the library MailKit. If you are using your own mail library (Or worse, trying to open the TCP ports yourself and manage the connections), you will need to sort of “translate” the fix to be applicable within your code.
Let’s go!
Default Ports
Before we go any further, it’s worth noting the “default” ports that SMTP is likely to use, and the settings that go along with them.
Port 25
25 is typically used a clear text SMTP port. Usually when you have SMTP running on port 25, there is no SSL and no TLS. So set your email client accordingly.
Port 465
465 is usually used for SMTP over SSL, so you will need to have settings that reflect that. However it does not use TLS.
Port 587
587 is usually used for SMTP when using TLS. TLS is not the same as SSL. Typically anything where you need to set SSL to be on or off should be set to off. This includes any setting that goes along the lines of “SSLOnConnect”. It doesn’t mean TLS is less secure, it’s just a different way of creating the connection. Instead of SSL being used straight away, the secure connection is “negotiated” after connection.
Settings that are relevant to port 587 usually go along the lines of “StartTLS” or simply “TLS”. Something like Mailkit usually handles TLS for you so you shouldn’t need to do anything extra.
Incorrect SMTP Host
System.Net.Sockets.SocketException: No such host is known
This one is an easy fix. It means that you have used an incorrect SMTP hostname (Usually just a typo). So for example using smp.gmail.com instead of smtp.gmail.com. It should be noted that it isn’t indicative that the port is wrong, only the host. See the next error for port issues!
Incorrect SMTP Port
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: A socket operation was attempted to an unreachable network [IpAddress]:[Port]
Another rather simple one to fix. This message almost always indicates you are connecting to a port that isn’t open. It’s important to distinguish that it’s not that you are connecting with SSL to a non SSL port or anything along those lines, it’s just an out and out completely wrong port.
It’s important that when you log the exception message of this error, you check what port it actually says in the log. I can’t tell you how many times I “thought” I was using a particular port, but as it turned out, somewhere in the code it was hardcoded to use a different port.
Another thing to note is that this error will manifest itsef as a “timeout”. So if you try and send an email with an incorrect port, it might take about 30 seconds for the exception to actually surface. This is important to note if your system slows to a crawl as it gives you a hint of what the issue could be even before checking logs.
Forcing Non-SSL On An SSL Port
MailKit.Net.Smtp.SmtpProtocolException: The SMTP server has unexpectedly disconnected.
I want to point out this is a MailKit exception, not one from .NET. In my experience this exception usually pops up when you set Mailkit to not use SSL, but the port itself requires SSL.
As an example, when connecting to Gmail, the port 465 is used for SSL connections. If I try and connect to Gmail with the following Mailkit code :
var emailClient = new SmtpClient(); emailClient.Connect("smtp.gmail.com", 465, false);
That last parameter that’s set to false is telling Mailkit to not use SSL. And what do you know, we get the above exception. The easy fix is obviously to change this to “true”.
Alternatively, you might be getting confused about TLS vs SSL. If the port says to connect using SSL, then you should not “force” any TLS connection.
Connecting Using SSL On A TLS Port (Sometimes)
MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.
Another Mailkit specific exception. This one can be a bit confusing, especially because the full error log from MailKit talks about certificate issues (Which it totally could be!), but typically when I see people getting this one, it’s because they are trying to use SSL when the port they are connecting to is for TLS. SSL != TLS.
So instead of trying to connect using MailKit by forcing SSL, just connect without passing in an SSL parameter.
emailClient.Connect("smtp.gmail.com", 465);
I should note that you will also get this exception in Mailkit if you try and force the SSLOnConnect option on a TLS Port. So for example, the following will not work :
emailClient.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.SslOnConnect);
Again, sometimes this is because the SSL connection truly is bogus (Either because the certificate is bad, expired etc), or because you are connecting to a port with no security whatsoever. But because of the rise of TLS, I’m going to say the most likely scenario is that you are trying to force SSL on a TLS port.
Another error that you can sometimes get with a similar setup is :
Handshake failed due to an unexpected packet format
This is an exception that has a whole range of causes, but the most common is forcing an SSL connection on a TLS port. If your SMTP port supports “TLS”, then do not set SSL to true.
Forcing No TLS On A TLS Port
System.NotSupportedException: The SMTP server does not support authentication.
This one is a little weird because you basically have to go right out of your way to get this exception. The only way I have seen this exception come up when you are telling Mailkit to go out of it’s way to not respect any TLS messages it gets and try and ram authentication straight away.
So for example, the following code would cause an issue :
emailClient.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.None);
Incorrect Username And/Or Password
MailKit.Security.AuthenticationException: AuthenticationInvalidCredentials: 5.7.8 Username and Password not accepted.
Goes without saying, you have the wrong username and password. This is not going to be any connection issues. You definitely have the right host and port, and the right SSL/TLS settings, but your username/password combination is wrong.
Other Errors?
Have something else going haywire? Drop a comment below!
MailKit.Security.AuthenticationException: AuthenticationInvalidCredentials: 5.7.3 Authentication unsuccessful .
This is one of the errors that constantly bugs me. Even after providing the correct userID and password and keeping RequiresAuthentication as True, it fails to send.
Hi. I have an issue sending smtp to port 465 on a remote mail server and it gets through very intermittently. One in 50 or something. No errors are logged in visual studio debugging. I’ve tried sending to the account from regular mail client and all good. Have you encountered anything similar??
Maybe sounds like a spam issue? When you say it gets through very intermittently, do you mean that you actually receive the email on the other end 1 in 50? If so, it’s highly likely it’s getting spammed. Especially if you don’t have SPF records setup for your custom domain etc.
Confirmed – its getting spammed. thanks for heads up! I’l have to look at getting the domain records managed, that’s another dev. The regular domain shows an SPF record, but this is using a subdomain, could be an issue. Champion effort.
Hello,
I am getting the following exception:
“ExtendedSocketException: 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”
If I use port 25 instead of 465 and don’t force the SSL, it works just fine.Any ideas?
Hmmm. Are you sure Port 465 is open? And has your mailer listening on this port? And ontop of that, whatever machine your code is running from (Say your IIS box), that has outbound port of 465 open too? If you can connect on port 25 (Assuming with Auth?), then it means that your auth details are correct, network connectivity is there, and the SMTP server is alive. So it has to be some sort of port blockage (Or your SMTP Server is not setup with SSL yet)
I received the following exception: “InvalidOperationException: No sender has been specified.”
This was thrown by the “emailClient.Send(message)” method, in the “Send” method defined in the EmailService class.
I solved it by setting a non-null MailBoxAddress on the message.Sender property.
Example:
message.Sender = message.From.First() as MailBoxAddress;
(ok, this line of code is horrible, but it’s just an example)
With such a fix it works properly, but I stay with the doubt that maybe there’s a more proper way…
Also getting this
Hello please I am getting the same error message, I have tried your option to resolving it but still did not seem to work. please what next would I have done?
When Using the ConnectAsync method i get following error: System.PlatformNotSupportedException: System.Net.Dns:GetHostByName is not supported on this platform.
If is use i use the normal connect method my page just crashes.
I dont know what to do.
Are you running this on Mono? If not, which platform are you running this on (Linux, Mac, Windows?). It’s possible your platform doesn’t have a implementation for that method. Typically it will be a particular flavor of Linux you are running on.
Getting MailKit.Net.Smtp.SmtpCommandException: 5.5.2 Syntax error. w138sm1213644vke.51
on GMAIL
Any ideas?
i am getting this error message
The mail system returned the following error: “A call to MailKit.Net.Smtp.SmtpClient.Connect failed with this message: The message received was unexpected or badly formatted”
Thanks a lot. it helped me a lot
Thank you very much. In my case it was deleting SSL parameter. And now it works. Many thanks again 🙂
I’m getting a AuthenticationInvalidCredentials: 5.7.3 Authentication unsuccessful error. I’ve tested that I’m using the correct credentials by copying the password out of my code and pasting it into a browser login — which works. What would cause this?
If you get this error it’s almost certainly still invalid credentials because it’s a specific SMTP response code from the server. Working in the browser may still work with that username and password because it works for the web only. For example when using sendgrid SMTP, you don’t use the username/password combo, instead the username is always “apikey” and the password is an actual API Key etc. Other services have similar paradigms where you generate a specific “key” that you pass in the password. So it’s going to depend on what service you are using.
I have used mailkit to send emails which works fine in my local system. But same when deployed in AWS gives unsuccessful authentication error. What’s the solution for this? Please support me.
I would probably start by debugging what it thinks the username/password is on AWS. Sometimes it’s a bad config transform etc. But an authentication issue is usually no wrong, it truly thinks your username and password is wrong.
MailKit.Net.Smtp.SmtpCommandException: 5.1.7 Invalid address
Hello Wade, I’ve been getting the exception above even though both sender and recipient are valid addresses.
I have no problem when Using Gmail, but after switching to Office365 (port 587) this starts to show up.
Looks like maybe just an Office365/Exchange issue https://bobcares.com/blog/how-to-fix-email-error-501-571-invalid-address/
good day, sending mail worked for me once, then only this message appears:
An error occurred during the connection attempt because the connected party did not automatically respond after a period of time, or an established connection failed because the connected host has not responded.
the tried to use port 25, 465,587 and I have no solution, the tried to add new firewall rules to open these ports and it doesn’t work either, if you could help me with your experience I really appreciate it.
This is the configuration I have:
thanks
If you are using this with yahoo mail, you will need to generate a password for your app.
Go to account security -> manage app passwords
At the bottom of “select your app” drop down list, click on “other app”
create an app name and password.
Use this when you Authenticate.
i get this error and idk what to do; i would really appreciate it if u can help me! MailKit.Security.SslHandshakeException : ‘An error occurred while attempting to establish an SSL or TLS connection.
The SSL certificate presented by the server is not trusted by the system for one or more of the following reasons:
1. The server is using a self-signed certificate which cannot be verified.
2. The local system is missing a Root or Intermediate certificate needed to verify the server’s certificate.
3. The certificate presented by the server is expired or invalid.
This is typically exactly as it’s described here, you are trying to connect to a mailserver using SSL when the certificate is not able to be validated.
Using port 25, email goes to junk folder.. Fixed that by using port 587. Thank you!
I’m getting this error
SmtpCommandException: 4.7.1 : Sender address rejected: not owned by user myAddress@company.com
You know what this can mean?
I posted the whole deal in StackOverflow: https://stackoverflow.com/questions/65184757/mailkit-net-core-sender-address-rejected-not-owned-by-user-error?noredirect=1#comment115239897_65184757
Hey, I am trying to connect to my inbox using IMAPClient with configuration
host: imap-mail.outlook.com,
port: 993
I get the following error:
System.IO.IOException: An established connection was aborted by the software in your host machine
I check and there are no NetFirewallPortFilter applied to port 993.
any idea how to solve this problem?
thanks in advance
We have Exchange hosted on multiple instances behind an ELB. When patching we take an instance out of the ELB and patch it offline. It seems that during this period connections that are established between the Mailkit client and Exchange on the out of ELB instance are still taking place to some extent. We have found that we get an increase in errors while the offline instance is rebooting but will stop when its up even if it has not been added to the load balancer. Not all traffic is failing but it is hard to say if the traffic that is successful is just that that is routing to the active instance.
This is the exception
at MailKit.Net.NetworkStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at System.Net.Security.SslStream.g__InternalFillBufferAsync|215_0[TReadAdapter](TReadAdapter adap, ValueTask`1 task, Int32 min, Int32 initial)
at System.Net.Security.SslStream.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)
All email addresses send ok and thanks for the info.
Except, only gmail destinations will bounce with the below error.
Any idea about this. I have included the send code far below
ERROR
—————————————————————————————-
Reporting-MTA: dns; sc107.eboundhost.com
Action: failed
Final-Recipient: rfc822;warren.trog@gmail.com
Status: 5.0.0
Remote-MTA: dns; gmail-smtp-in.l.google.com
Diagnostic-Code: smtp; 550-5.7.1 [69.27.46.100 14] Messages missing a valid address in From:
550 5.7.1 header, or having no From: header, are not accepted. j1si12280236jat.46 – gsmtp
—————————————————————————————————————————————————-
Error when sending email. Get a message about name does not match the certificate. If I use the same server name with the System.Net.Mail SMTPClient, it works. This is using MS Exchange.