C#应用使用MimeKit通过SES SMTP(端口25)发邮件失败求助
问题:使用MimeKit通过SES端口25发送邮件时证书吊销检查失败
我开发了一个用MimeKit通过Amazon SES发送邮件的C#应用,服务器仅允许使用端口25,实现代码如下:
public virtual bool Send(MimeMail mimeMail) { try { mimeMailSmtpClient = new MailKit.Net.Smtp.SmtpClient(); mimeMailSmtpClient.Connect("email-smtp.us-west-2.amazonaws.com", 25, SecureSocketOptions.StartTls); mimeMailSmtpClient.Authenticate(serverUsername, serverPassword); mimeMailSmtpClient.Send(mimeMail.GetMessageItem()); mimeMailSmtpClient.Disconnect(true); return true; } catch (Exception ex) { var msg = ex.Message; return false; } }
执行邮件发送功能时,收到如下错误:
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. • The revocation function was unable to check revocation because the revocation server was offline. • An intermediate certificate has the following errors: • The revocation function was unable to check revocation for the certificate. • The revocation function was unable to check revocation because the revocation server was offline. • An intermediate certificate has the following errors: • The revocation function was unable to check revocation for the certificate. • The revocation function was unable to check revocation because the revocation server was offline. • An intermediate certificate has the following errors: • The revocation function was unable to check revocation for the certificate. • The revocation function was unable to check revocation because the revocation server was offline.
我通过PowerShell连接Amazon SES SMTP服务器时能成功建立连接,但C#代码却报错,请问我的代码是否遗漏了必要的配置?
解答
问题根源是MimeKit的SmtpClient默认会强制检查SSL证书的吊销状态,而你的服务器环境无法访问证书吊销列表(CRL)服务器,导致验证失败。PowerShell能成功是因为它的证书验证策略默认不强制要求吊销检查,或者其环境可以正常访问CRL服务器。
你需要添加证书验证回调来调整验证逻辑,跳过吊销检查。同时建议用using语句自动释放客户端资源,避免泄漏。修改后的代码如下:
public virtual bool Send(MimeMail mimeMail) { try { using (var mimeMailSmtpClient = new MailKit.Net.Smtp.SmtpClient()) { // 自定义证书验证逻辑,跳过吊销检查 mimeMailSmtpClient.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => { // 仅排除吊销相关的错误,保留其他证书有效性检查(推荐) var invalidErrors = errors & ~(SslPolicyErrors.RemoteCertificateChainErrors & (SslPolicyErrors.RemoteCertificateRevocationCheckFailed | SslPolicyErrors.RemoteCertificateUnknownRevocation)); return invalidErrors == SslPolicyErrors.None; // 若确认SES证书绝对可信,也可以直接返回true(生产环境谨慎使用) // return true; }; mimeMailSmtpClient.Connect("email-smtp.us-west-2.amazonaws.com", 25, SecureSocketOptions.StartTls); mimeMailSmtpClient.Authenticate(serverUsername, serverPassword); mimeMailSmtpClient.Send(mimeMail.GetMessageItem()); mimeMailSmtpClient.Disconnect(true); return true; } } catch (Exception ex) { var msg = ex.Message; return false; } }
注意事项
- 优先使用保留基础证书验证的逻辑,只跳过吊销检查,避免完全关闭验证带来的安全风险。
- 如果是生产环境,建议排查为何无法访问CRL服务器(比如防火墙、代理限制),从根源解决问题,而非绕过验证。
内容的提问来源于stack exchange,提问作者brendan davton
相关产品推荐
相关产品推荐

