locked
InvalidOperationException: An error occurred while attempting to establish an SSL or TLS connection. RRS feed

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

    Wednesday, June 26, 2019 1:30 PM

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 Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 26, 2019 2:05 PM
  • 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
    Wednesday, June 26, 2019 3:05 PM

All replies

  • User475983607 posted

    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 assume you need to enable SSL and set the proper SSL port according to your SMPT server.

    I recommend setting a break point and single stepping through the code.

    Wednesday, June 26, 2019 1:38 PM
  • User-501297529 posted

    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"
      }

    Wednesday, June 26, 2019 1:41 PM
  • User753101303 posted

    Hi,

    I would expect an inner exception which is hidden by using throw new InvalidOperationException(ex.Message);

    Just use throw; or get rid of this useless try/catch. It should then show usefull additional details about the problem.

    Wednesday, June 26, 2019 1:58 PM
  • 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 Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 26, 2019 2:05 PM
  • User-501297529 posted

    Hi,

    I would expect an inner exception which is hidden by using throw new InvalidOperationException(ex.Message);

    Just use throw; or get rid of this useless try/catch. It should then show usefull additional details about the problem.

    I removed the try/catch and throw. Not sure if I should have removed all three. 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'

    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?

    using FE.Entitiies;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Options;
    using MimeKit;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;       //NetworkCredential
    //using System.Net.Mail;  //SmtpClient
    using System.Threading.Tasks;
    using MailKit.Net.Smtp;
    
    namespace FE.Services
    {
        public interface IEmailSender
        {
            Task SendEmailAsync(string email, string subject, string message);
        }
    
        public class EmailSender : IEmailSender
        {
            private readonly EmailSettings _emailSettings;
            private readonly IHostingEnvironment _env;
    
            public EmailSender(
                IOptions<EmailSettings> emailSettings,
                IHostingEnvironment env)
            {
                _emailSettings = emailSettings.Value;
                _env = env;
            }
    
            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);
                //}
            }
        }
    }

    Wednesday, June 26, 2019 2:32 PM
  • 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
    Wednesday, June 26, 2019 3:05 PM
  • User-501297529 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.

    bootzilla

    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.  

    bootzilla

    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.

    Nevermind I got it to work. Thanks for all of your help, everyone.

    Wednesday, June 26, 2019 3:15 PM