【问题标题】:How do I send an email with a SSL certificate?如何发送带有 SSL 证书的电子邮件?
【发布时间】:2018-04-15 18:10:14
【问题描述】:

我在发送带有 SSL 证书的电子邮件时遇到了一些问题。 我知道有第三方可以使用,但出于不想讨论的原因,我不能使用这些。

目前我正在使用

System.Net.Sockets
发送电子邮件。据我了解,这种方法无法通过 SSL 发送电子邮件。所以我遇到了
System.Net.Security.SslStream
并找到了一些示例代码来演示如何执行此操作。

在 STARTTLS 命令之后,我正在创建一个 SslStream。这可行,但是当我进行握手时,我收到错误消息:由于意外的数据包格式,握手失败。

这是我创建 SSLStream 并进行握手的代码。

private SslStream _sslStream = null;
private NetworkStream _networkStream = null;
private TcpClient _client = null;
private bool _SSLActive = false;

public SmtpConnectorWithSSL(string smtpServerAddress, int port) : base(smtpServerAddress, port)
        {
            _client = new TcpClient(smtpServerAddress, port);
            _networkStream = _client.GetStream();
        }    

public override void CreateSSLConnection()
        {
            _sslStream = new SslStream(
                _networkStream,
                true,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                );

            // The server name must match the name on the server certificate.
            try
            {
                _sslStream.AuthenticateAsClient(SmtpServerAddress, GetX509CertificateCollection(), SslProtocols.Tls, false);

                _SSLActive = true;
            }
            catch (AuthenticationException e)
            {
                _sslStream = null;
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                _client.Close();
            }
            catch (Exception ex)
            {
                _sslStream = null;
                Console.WriteLine("Error: {0}", ex.Message);
                _client.Close();
            }
        }

错误发生在“AuthenticateAsClient()”函数中。

也许这与我正在加载的证书有关?

public static X509CertificateCollection GetX509CertificateCollection()
    {
        X509Certificate2 certificate1 = new X509Certificate2(@"C:\Users\leo\OneDrive - Cumulo9 Limited\Documents\Cumulo9\StartCom\mailprimer.com\IISServer\2_mailprimer.com.crt");
        X509CertificateCollection collection1 = new X509CertificateCollection();
        collection1.Add(certificate1);
        return collection1;
    }

也许证书是错误的,但我不知道如何找出来。我希望错误消息会有所不同。

如果有帮助的话,我可以将整个示例项目提供给您。

感谢您的帮助。

【问题讨论】:

  • “在 STARTTLS 命令之后,我正在创建一个 SslStream。” - 在您发送 STARTTLS 命令之后还是在您成功响应命令之后?
  • 抱歉,在收到“220 Ready to start TLS”响应后,我应该说。

标签: c# sockets ssl smtp


【解决方案1】:

此问题的解决方案是收件人服务器的超时时间为 1 秒。握手持续了超过 1 秒,因此引发了异常。收件人电子邮件服务器将超时时间更改为 30 秒后,握手成功。

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 2014-01-29
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多