Search code examples
ssljakarta-mailself-signedstarttls

Javamail STARTTLS with self-signed certificate using Spring container


I am trying to connect to an SMTP server (James 3) with a self-signed certificate on port 25 with STARTTLS switched on.

I have enabled JavaMail properties to trust all hosts but I still get a PKIX certificate path validation error. How can I get rid of the error?

See the code below.

   //Trust all hosts
    MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.starttls.required", "true");
    props.put("mail.smtp.auth.mechanisms", "PLAIN");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.ssl.socketFactory", sf);

    Session session = Session.getInstance(props, null);

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(ti.sutUserName));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(ti.sutEmailAddress));


        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("This is message body");

        Multipart multipart = new MimeMultipart();



        log.info("Sending Message");

        Transport transport = session.getTransport("smtp");
        transport.connect(ti.sutSmtpAddress, ti.sutUserName, ti.sutPassword);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();`

Solution

  • I was using Javamail API (Compact) 1.4 inside a Spring Boot container which has Javamail 1.5.3 by default. After I changed my jar to 1.5.3, the program started to work fine.

    See: Spring Boot 1.2.5.RELEASE - Sending E-mail via Gmail SMTP

    Thanks for your help.