【发布时间】: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”响应后,我应该说。