【问题标题】:JavaMail SSL with no Authentication trust certificate regardless没有身份验证信任证书的 JavaMail SSL
【发布时间】:2014-02-24 16:06:32
【问题描述】:

我有一个带有 SSL(端口 465)和自签名证书的本地邮件服务器 (hMailServer)。

域名是“foobar.com”

我已设置我的Properties 以启用 ssl、禁用身份验证并信任任何主机

    props.put("mail.smtp.auth", "false");
    props.put("mail.smtp.ssl.enable", "true");
    props.put("mail.smtp.ssl.trust", "*");

如果我通过静态调用将消息发送到Transport.send() 电子邮件已送达。

如果我尝试从会话中获取 transport 实例,那么我会得到

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

静态调用如何避免 SSLHandshakeException?

这是我的测试代码:

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.put("mail.smtp.host", "127.0.0.1");
    props.put("mail.debug", "false");
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.timeout", "60000");
    props.put("mail.smtp.auth", "false");
    props.put("mail.smtp.sendpartial", "true");
    props.put("mail.smtp.ssl.enable", "true");
    props.put("mail.smtp.ssl.trust", "*");
    Session session = Session.getInstance(props);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("mrFoo@foobar.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("you@foobar.com"));
    message.setSubject("Just a Test " + new Date());
    message.setText("Hello World");

    //Comment and uncomment to test   
    Transport.send(message, message.getAllRecipients());

    //Transport t = session.getTransport("smtps");
    //t.connect();
    //t.sendMessage(message, message.getAllRecipients());
    //t.close();
}

这是一个从外部隐藏的本地系统,所以我不担心中间人攻击生成自己的证书以绕过 SSL 握手...

【问题讨论】:

    标签: java smtp jakarta-mail


    【解决方案1】:

    这是使用 Spring 框架的没有身份验证信任证书的 JavaMail SSL 的解决方案,如下所述更改您的 .xml 文件。您可以在快照 See the image description here 中查看解决方案

    javax.net.ssl.SSLSocketFactory 真的

    如果您希望邮件服务器必须在 ssl 中,请将其更改为 false

    【讨论】:

      【解决方案2】:

      最好的解决方案是使用以下行

          MailSSLSocketFactory socketFactory = new MailSSLSocketFactory();
          socketFactory.setTrustAllHosts(true);
      

      【讨论】:

        【解决方案3】:

        您要求“smtps”传输。您设置“smtp”传输的属性。由于您已将“mail.smtp.ssl.enable”属性设置为“true”,因此您只需请求“smtp”传输,它将使用 SSL。

        【讨论】:

        • 也就是在代码sn-p末尾的out注释行中做Transport t = session.getTransport("smtp")而不是..."smtps"),对吧。
        猜你喜欢
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-03
        • 1970-01-01
        • 2011-11-11
        • 2023-03-02
        • 1970-01-01
        相关资源
        最近更新 更多