JavaMail SSL with no Authentication trust certific

2019-02-17 20:49发布

I have a local mail server (hMailServer) with SSL (port 465) and a self-signed certificate.

Domain is "foobar.com"

I have setup my Properties to enable ssl, disable auth, and trust any host

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

If I send the message through the static call to Transport.send() The email gets delivered.

If I try to get a transport instance from the session then I get

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

How does the static call avoids the SSLHandshakeException?

Here's my tester code:

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();
}

This is a local system hidden from the outside, so I am not worried about man in the middle attack generating their own certificates to bypass the SSL Handshake...

3条回答
在下西门庆
2楼-- · 2019-02-17 21:26

The best solution for this is to use the following line

    MailSSLSocketFactory socketFactory = new MailSSLSocketFactory();
    socketFactory.setTrustAllHosts(true);
查看更多
Juvenile、少年°
3楼-- · 2019-02-17 21:27

You asked for an "smtps" transport. You set the properties for the "smtp" transport. Since you've set the "mail.smtp.ssl.enable" property to "true", you can just ask for an "smtp" transport and it will use SSL.

查看更多
欢心
4楼-- · 2019-02-17 21:28

This the solution for JavaMail SSL with no Authentication trust certificate using Spring framework, change your .xml file as describe below.You can see the solution in the snapshot See the image description here

javax.net.ssl.SSLSocketFactory true

change it to false if you want mail server must be in ssl

查看更多
登录 后发表回答