Here’s a copy & paste from the MailKit FAQ:
Q: Why do I get "MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection."
when I try to Connect?
When you get an exception with that error message, it usually means that you are encountering
one of the following scenarios:
1. The mail server does not support SSL on the specified port.
There are 2 different ways to use SSL/TLS encryption with mail servers.
The first way is to enable SSL/TLS encryption immediately upon connecting to the
SMTP, POP3 or IMAP server. This method requires an «SSL port» because the standard
port defined for the protocol is meant for plain-text communication.
The second way is via a STARTTLS
command (aka STLS
for POP3) that is optionally
supported by the server.
Below is a table of the protocols supported by MailKit and the standard plain-text ports
(which either do not support any SSL/TLS encryption at all or only via the STARTTLS
command extension) and the SSL ports which require SSL/TLS encryption immediately upon a
successful connection to the remote host.
|Protocol|Standard Port|SSL Port|
|:------:|:-----------:|:------:|
| SMTP | 25 or 587 | 465 |
| POP3 | 110 | 995 |
| IMAP | 143 | 993 |
It is important to use the correct SecureSocketOptions
for the port that you are connecting to.
If you are connecting to one of the standard ports above, you will need to use SecureSocketOptions.None
,
SecureSocketOptions.StartTls
or SecureSocketOptions.StartTlsWhenAvailable
.
If you are connecting to one of the SSL ports, you will need to use SecureSocketOptions.SslOnConnect
.
You could also try using SecureSocketOptions.Auto
which works by choosing the appropriate option to use
by comparing the specified port to the ports in the above table.
2. The mail server that you are connecting to is using an expired (or otherwise untrusted) SSL certificate.
Often times, mail servers will use self-signed certificates instead of using a certificate that
has been signed by a trusted Certificate Authority. Another potential pitfall is when locally
installed anti-virus software replaces the certificate in order to scan web traffic for viruses.
When your system is unable to validate the mail server’s certificate because it is not signed
by a known and trusted Certificate Authority, the above error will occur.
You can work around this problem by supplying a custom RemoteCertificateValidationCallback
and setting it on the client’s ServerCertificateValidationCallback
property.
In the simplest example, you could do something like this (although I would strongly recommend against it in
production use):
using (var client = new SmtpClient ()) {
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.Connect (hostName, port, SecureSocketOptions.Auto);
// ...
}
Most likely you’ll want to instead compare the certificate’s Thumbprint
property to a known value that you have verified at a prior date.
You could also use this callback to prompt the user (much like you have probably seen web browsers do)
as to whether or not the certificate should be trusted.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
Most Certificate Authorities are probably pretty good at keeping their CRL and/or OCSP servers up 24/7, but occasionally
they do go down or are otherwise unreachable due to other network problems between you and the server. When this happens,
it becomes impossible to check the revocation status of one or more of the certificates in the chain.
To ignore revocation checks, you can set the
CheckCertificateRevocation
property of the IMAP, POP3 or SMTP client to false
before you connect:
using (var client = new SmtpClient ()) {
client.CheckCertificateRevocation = false;
client.Connect (hostName, port, SecureSocketOptions.Auto);
// ...
}
4. The server does not support the same set of SSL/TLS protocols that the client is configured to use.
MailKit attempts to keep up with the latest security recommendations and so is continuously removing older SSL and TLS
protocols that are no longer considered secure from the default configuration. This often means that MailKit’s SMTP,
POP3 and IMAP clients will fail to connect to servers that are still using older SSL and TLS protocols. Currently,
the SSL and TLS protocols that are not supported by default are: SSL v2.0, SSL v3.0, and TLS v1.0.
You can override MailKit’s default set of supported
SSL and TLS protocols
by setting the value of the SslProtocols
property on your SMTP, POP3 or IMAP client.
For example:
using (var client = new SmtpClient ()) {
// Allow SSLv3.0 and all versions of TLS
client.SslProtocols = SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;
client.Connect ("smtp.gmail.com", 465, true);
// ...
}
Hi Everyone,
I am trying to send e-mails using MailKit in my project with .net core. I have the following settings in the Core (Domain) project:
public class AppSettingProvider : SettingProvider
{
public override IEnumerable<SettingDefinition> GetSettingDefinitions(SettingDefinitionProviderContext context)
{
return new[]
{
new SettingDefinition(AppSettingNames.UiTheme, "red", scopes: SettingScopes.Application | SettingScopes.Tenant | SettingScopes.User, isVisibleToClients: true),
new SettingDefinition(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, "true", scopes: SettingScopes.Application, isVisibleToClients: false),
// E-mail settings
new SettingDefinition(EmailSettingNames.DefaultFromAddress, "noreplay@test.com.mx", scopes: SettingScopes.Application, isVisibleToClients: false),
new SettingDefinition(EmailSettingNames.DefaultFromDisplayName, "Test", scopes: SettingScopes.Application, isVisibleToClients: false),
new SettingDefinition(EmailSettingNames.Smtp.Host, "localhost", scopes: SettingScopes.Application, isVisibleToClients: false),
new SettingDefinition(EmailSettingNames.Smtp.Port, "25", scopes: SettingScopes.Application, isVisibleToClients: false),
new SettingDefinition(EmailSettingNames.Smtp.EnableSsl, "false", scopes: SettingScopes.Application, isVisibleToClients: false)
};
}
}
I am trying to do this in my UserManager class:
public override async Task<IdentityResult> CreateAsync(User user)
{
Task<IdentityResult> identityResult = base.CreateAsync(user);
// Send user confirmation e-mail
try
{
await _emailSender.SendAsync(user.EmailAddress, "Active Account Test", "Testing", true);
}
catch (Exception ex)
{
throw new UserFriendlyException(ex.Message);
}
return await identityResult;
}
When the code _emailSender.SendAsync runs, I am getting this error:
An error occurred while attempting to establish an SSL or TLS connection.rnrnThe SSL certificate presented by the server is not trusted by the system for one or more of the following reasons:rn1. The server is using a self-signed certificate which cannot be verified.rn2. The local system is missing a Root or Intermediate certificate needed to verify the server’s certificate.rn3. The certificate presented by the server is expired or invalid.rnrnSee https://github.com/jstedfast/MailKit/blob/master/FAQ.md#InvalidSslCertificate for possible solutions.
Do you know what I am missing?
I really appreciate your help.
Thanks!!!
Содержание
- SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection
- 4 Answers 4
- Q: Why do I get «MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.» when I try to Connect?
- 1. The mail server does not support SSL on the specified port.
- 2. The mail server that you are connecting to is using an expired (or otherwise untrusted) SSL certificate.
- 3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
- 4. The server does not support the same set of SSL/TLS protocols that the client is configured to use.
- MailKit.Security.SslHandshakeException misleading error actually due to missing libcurl library #735
- Comments
- Unable to send emails via Mailkit on an Azure web app
- 1 Answer 1
- Getting error while sending email in Asp.net core ( An error occurred while attempting to establish an SSL or TLS connection. )
- 1 Answer 1
- Related
- Hot Network Questions
- Subscribe to RSS
- MailKit.Security.SslHandshakeException: The host name did not match the name given in the server’s SSL certificate. ASP.NET Core, Nginx
- 2 Answers 2
SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection
I’m trying to access gmail emails using imap and the code is failing at the ssl handshake without showing me any errors. Really appreciate if anyone could please help with this. I’ve built this using xunit, .NET Core 2.1. I’m using MailKit Nuget
4 Answers 4
Here’s a copy & paste from the MailKit FAQ:
Q: Why do I get «MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.» when I try to Connect?
When you get an exception with that error message, it usually means that you are encountering one of the following scenarios:
1. The mail server does not support SSL on the specified port.
There are 2 different ways to use SSL/TLS encryption with mail servers.
The first way is to enable SSL/TLS encryption immediately upon connecting to the SMTP, POP3 or IMAP server. This method requires an «SSL port» because the standard port defined for the protocol is meant for plain-text communication.
The second way is via a STARTTLS command (aka STLS for POP3) that is optionally supported by the server.
Below is a table of the protocols supported by MailKit and the standard plain-text ports (which either do not support any SSL/TLS encryption at all or only via the STARTTLS command extension) and the SSL ports which require SSL/TLS encryption immediately upon a successful connection to the remote host.
It is important to use the correct SecureSocketOptions for the port that you are connecting to.
If you are connecting to one of the standard ports above, you will need to use SecureSocketOptions.None , SecureSocketOptions.StartTls or SecureSocketOptions.StartTlsWhenAvailable .
If you are connecting to one of the SSL ports, you will need to use SecureSocketOptions.SslOnConnect .
You could also try using SecureSocketOptions.Auto which works by choosing the appropriate option to use by comparing the specified port to the ports in the above table.
2. The mail server that you are connecting to is using an expired (or otherwise untrusted) SSL certificate.
Often times, mail servers will use self-signed certificates instead of using a certificate that has been signed by a trusted Certificate Authority. Another potential pitfall is when locally installed anti-virus software replaces the certificate in order to scan web traffic for viruses.
When your system is unable to validate the mail server’s certificate because it is not signed by a known and trusted Certificate Authority, the above error will occur.
You can work around this problem by supplying a custom RemoteCertificateValidationCallback and setting it on the client’s ServerCertificateValidationCallback property.
In the simplest example, you could do something like this (although I would strongly recommend against it in production use):
Most likely you’ll want to instead compare the certificate’s Thumbprint property to a known value that you have verified at a prior date.
You could also use this callback to prompt the user (much like you have probably seen web browsers do) as to whether or not the certificate should be trusted.
3. A Certificate Authority CRL server for one or more of the certificates in the chain is temporarily unavailable.
Most Certificate Authorities are probably pretty good at keeping their CRL and/or OCSP servers up 24/7, but occasionally they do go down or are otherwise unreachable due to other network problems between you and the server. When this happens, it becomes impossible to check the revocation status of one or more of the certificates in the chain.
To ignore revocation checks, you can set the CheckCertificateRevocation property of the IMAP, POP3 or SMTP client to false before you connect:
4. The server does not support the same set of SSL/TLS protocols that the client is configured to use.
MailKit attempts to keep up with the latest security recommendations and so is continuously removing older SSL and TLS protocols that are no longer considered secure from the default configuration. This often means that MailKit’s SMTP, POP3 and IMAP clients will fail to connect to servers that are still using older SSL and TLS protocols. Currently, the SSL and TLS protocols that are not supported by default are: SSL v2.0, SSL v3.0, and TLS v1.0.
You can override MailKit’s default set of supported SSL and TLS protocols by setting the value of the SslProtocols property on your SMTP, POP3 or IMAP client.
Источник
MailKit.Security.SslHandshakeException misleading error actually due to missing libcurl library #735
This was a vexing problem that I found a solution for and am posting in case anyone else runs into this issue.
I have a asp.net Core 2.1 project with Mailkit 2.0.5 on Ubuntu 16.04.4 and a Surgemail mail server we host ourselves.
The application is an internal company app that uses IMAP to check for mail and display it in a web page. It worked fine on a Windows server for months. We recently ported our online services to Linux so I installed it on Linux with the .net 2.1 runtime and got the error stack trace in the block below when using IMAP to connect to the mail server.
Because the error specifically states it’s a certificate issue I spent a lot of time trying many different things including opening the mail server non SSL port for IMAP and turning off SSL in my code completely, everything worked no matter what I did on my local Windows dev station but not on the Linux server.
When I completely turned off SSL in MailKit and also overrode the certificate check and it still gave the same error about the certificate I knew something more was up.
The resolution turned out to be a missing pre-requisite that was not installed with the .net runtime libcurl.
After running the following command it immediately started working without error:
apt-get install libcurl3
So it seems .net 2.1 runtime installation doesn’t actually install all the pre-requisites required for Mailkit.
It’s a bit strange that this particular error message comes up when a library is missing and all SSL options are turned off.
I hope this helps someone else in future.
The text was updated successfully, but these errors were encountered:
Источник
Unable to send emails via Mailkit on an Azure web app
Within our organization we’re developing a web app ( .NET Core 2.0 ) which is hosted in an Azure App Service. For our emailing infrastructure, we’ve installed the latest version of MailKit (version 2.11.1 at the time of writing).
Locally, the process of sending emails works properly and no problems occur, however, after deploying the app to our Azure environment an SslHandshakeException is thrown upon connecting.
We’re using the following configuration (simplified):
We’ve tried playing around with different configuration values (e.g. other ports) but without success.
What did seem to work, though, is downgrading the MailKit package to version 2.3.1.6 . Without any configurational changes, the connection did succeed and we were able to send emails.
Could someone explain why the versions behave differently and what steps we possibly need to take to make our configuration work with the newest version of MailKit ?
Thanks in advance!
1 Answer 1
MailKit 2.3.1.6 had a default SSL certificate validation callback that was much more liberal in what it accepted as valid.
Newer versions of MailKit do not (in other words, newer versions of MailKit focus on security rather than «just connect to the damn server, I don’t care if the SSL certificates are valid or not»). Instead, MailKit now hard-codes the serial numbers and fingerprints of some of the more common mail servers (such as GMail, Yahoo!Mail, Office365 and some others) to make this «magically» work most of the time for people. However, as you have discovered, sometimes these certificates get renewed and the hard-coded values that MailKit has are no longer up-to-date (just released 2.12.0 which updates them, btw).
The best way to solve this is to set your own ServerCertificateValidationCallback on the SmtpClient:
To help you debug the issue, your callback method could look something like this:
One possible solution to your issue, depending on what the problem is, might be something like this:
Источник
Getting error while sending email in Asp.net core ( An error occurred while attempting to establish an SSL or TLS connection. )
I am workin on project using asp.net core 3.1 , also i am using design pattern in my work.
when i try to send email using smtp i got this error .
An error occurred while attempting to establish an SSL or TLS connection. The server’s SSL certificate could not be validated for the following reasons: • The server certificate has the following errors: • The revocation function was unable to check revocation for the certificate.
This is my code .
the error happened after this line .
1 Answer 1
The revocation function was unable to check revocation for the certificate.
This is usually a transient error caused by the CRL server being offline or otherwise unreachable at the time when you tried to establish and SSL/TLS connection and so the SslStream was unable to validate the server’s SSL certificate.
The CRL server is the central authority that provides a way for clients to check if a certificate has been revoked or not.
You can disable certificate revocation checks using the following snippet of code before calling the Connect method:
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
MailKit.Security.SslHandshakeException: The host name did not match the name given in the server’s SSL certificate. ASP.NET Core, Nginx
When I try to send an email message via Google and the MailKit library on a production containerized application I get this exception:
MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection. The host name did not match the name given in the server’s SSL certificate.
I use ASP.NET Core 5 and Kestrel. Nginx is my reverse proxy. SSL works fine when I get data using Postman. But when I try to send mail, the exception occurs. In a development environment without the Nginx server the proxy works properly.
This is my nginx.conf file:
This is my Program.cs file:
This is my Startup.cs file:
2 Answers 2
You can disable SSL/TLS by
Looks like a problem with the certificate or the mail host you are using to connect. To confirm, do this before connecting:
This will bypass the certificate validation and should resolve the error. However, if you care about security (and you should), don’t leave it like this. Instead, implement the callback method to figure out why validation is failing. A sample implementation is given here. I’ve reproduced the relevant code below.
You’ll want to set a callback like we did above:
Here’s the custom callback implementation:
Put some logging or a breakpoint in this method and step through it to see what certificate is being used, its properties, and where the validation is failing. This should help guide you to the actual source of the problem so you can resolve it.
Note: Depending on your MailKit version, the certificate and chain parameters may be defined as nullable.
Источник
Всем привет. Пишу приложение на ASP.NET Core. Использую MailKit для отправки почты.
Проблема такова: невозможно подключиться к SMTP серверу (причину так и не понял).
Решил использовать SSL. Код:
C# | ||
|
Ошибка:
An error occurred while attempting to establish an SSL or TLS connection.
One possibility is that you are trying to connect to a port which does not support SSL/TLS.
The other possibility is that the SSL certificate presented by the server is not trusted by the system for one or more of the following reasons:
The server is using a self-signed certificate which cannot be verified.
The local system is missing a Root or Intermediate certificate needed to verify the server’s certificate.
The certificate presented by the server is expired or invalid.
See https://github.com/jstedfast/M… ertificate for possible solutions.
Произошла ошибка при попытке установить соединение SSL или TLS.
Возможно, вы пытаетесь подключиться к порту, который не поддерживает SSL / TLS.
Другая возможность состоит в том, что сертификат SSL, представленный сервером, не является доверенным для системы по одной или нескольким из следующих причин:
Сервер использует самозаверяющий сертификат, который невозможно проверить.
В локальной системе отсутствует корневой или промежуточный сертификат, необходимый для проверки сертификата сервера.
Срок действия сертификата, предоставленного сервером, истек или недействителен.
См. Https://github.com/jstedfast/M… ertificate для возможных решений.
Смотрел по ссылке. Решение не помогло.
Решил сделать так, как описано здесь: https://metanit.com/sharp/aspnet5/16.5.php
Не помогло.
И что более странно, то, что пару раз письмо отправлялось, но позже перестало.
Пробовал указать другие порты, не помогло. Я так и не понял, в чем дело.
Буду рад слышать ваши ответы.
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
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!
- Remove From My Forums
-
Question
-
User-501297529 posted
I get this error message when trying to send email using TFA.
IEmailSender.cs
public async Task SendEmailAsync(string email, string subject, string message) { try { var mimeMessage = new MimeMessage(); mimeMessage.From.Add(new MailboxAddress(_emailSettings.SenderName, _emailSettings.Sender)); mimeMessage.To.Add(new MailboxAddress(email)); mimeMessage.Subject = subject; mimeMessage.Body = new TextPart("html") { Text = message }; using (var client = new SmtpClient()) { // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; if (_env.IsDevelopment()) { // The third parameter is useSSL (true if the client should make an SSL-wrapped // connection to the server; otherwise, false). await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, true); } else { await client.ConnectAsync(_emailSettings.MailServer); } // Note: only needed if the SMTP server requires authentication await client.AuthenticateAsync(_emailSettings.Sender, _emailSettings.Password); await client.SendAsync(mimeMessage); await client.DisconnectAsync(true); } } catch (Exception ex) { // TODO: handle exception throw new InvalidOperationException(ex.Message); } }
Controller
public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); }
Answers
-
User475983607 posted
bootzilla
mgebhard
The SMTP server is being set according to the environment.
if (_env.IsDevelopment()) { // The third parameter is useSSL (true if the client should make an SSL-wrapped // connection to the server; otherwise, false). await client.ConnectAsync(_emailSettings.MailServer, _emailSettings.MailPort, true); } else { await client.ConnectAsync(_emailSettings.MailServer); }
The community does not know the environment, the the value of _emailSettings.MailServer, and cannot see your appsettings.json files. I recommend setting a break point and single stepping through the code.
I figured this out in the appsettings file by changing mail server. Now I get ‘InvalidOperationException: An error occurred while attempting to establish an SSL or TLS connection’ error.
Here are my email setting in appsettings
"EmailSettings": { "MailServer": "smtp-mail.outlook.com", "MailPort": 587, "SenderName": "some name", "Sender": "some_email@some_server.com", "Password": "some_password" }
Still, we’re missing information. Is this the development environment as any other environment does not use a port or TLS.
Anyway, see the following MailKit issue post.
https://github.com/jstedfast/MailKit/issues/735
And, I agree with PatriceSc, do not obfuscate errors messages.
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User475983607 posted
I recommend creating a Console application to test SMTP. It’s a lot easier to run a console app after making changes. Once you get it working then copy the code to the web app.
I get ‘SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host
has failed to respond’Means an issue connection to the SMTP server. There’s many reasons for this, typo, firewall, virus checkers, etc.
I didn’t include the using in my original post with the IEmailSender.cs but does it matter what SmtpClient i’m using for this. Currently using MailKit.Net.Smtp and have System.Net.Mail commented
out. Does that matter? is that what is causing the error?It matters for the folks trying to help you as we need to read the reference documentation to make sure the code is correct.
-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by