Getting SmtpClient to work with a self signed SSL certificate

前端 未结 3 964
别跟我提以往
别跟我提以往 2021-01-17 13:58

I\'m attempting to use the System.Net.Mail.SmtpClient class to relay an email through my company\'s email server. All SMTP connections to the mail server have to be SSL and

相关标签:
3条回答
  • 2021-01-17 14:15

    You may take a look at the ServerCertificateValidationCallback property:

    ServicePointManager.ServerCertificateValidationCallback = 
        (sender, certificate, chain, sslPolicyErrors) => true;
    

    It represents a callback which is called by the runtime when it tries to validate an SSL certificate. By returning true you basically say that you don't care if the certificate is valid or not -> you always accept it. Of course having self signed certificates in production environment is not a good idea.

    0 讨论(0)
  • 2021-01-17 14:20

    If you want to be more secure, you might want to look at doing the following:

    theClient.EnableSsl = true;
    
    ServicePointManager.ServerCertificateValidationCallback =
        (sender, certificate, chain, sslPolicyErrors) => {
            if (sender == theClient) {
                return true;
            } else {
                // you should apply the code from this SO answer
                // https://stackoverflow.com/a/25895486/795690
                // if you find that anything in your app uses this path
                throw new ApplicationException("Certificate validation is currently disabled, extra code neeeded here!");
            }
        };
    
    

    In this code we are auto-approving certificates only for the specific SMTP client in question; we have a stub code path which you should upgrade to explicitly reinstate default certificate validation if you find that anything else in your app is using it.

    Another different, useful approach to approving certificates only in contexts where you actually want to is in this SO answer.

    0 讨论(0)
  • 2021-01-17 14:27

    My issue ended up being that the .Net SmtpClient class apparently doesn't support the use of port 465 for SMTP SSL connections. Using port 25 with a self signed SSL certificate worked correctly.

    MSDN System.Net forum question Can SmtpClient be configured to work with a self signed certificate?.

    0 讨论(0)
提交回复
热议问题