0

I got the SSLHandshakeException by using Spring Boot Mail Sender API. I have specified all the code snippets and properties files I have written below. What should I do to fix this error?

Log Errors

Mail sending is started
Error occured: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Process finished with exit code 0

application properties

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username= myemail
spring.mail.password= mypass
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Service layer

@Service
public class SendEmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendEmail(String to, String body, String topic){
        try {
            System.out.println("Mail sending is started");
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom("mail@mail.com");
            simpleMailMessage.setTo(to);
            simpleMailMessage.setSubject(topic);
            simpleMailMessage.setText(body);
            javaMailSender.send(simpleMailMessage);
            System.out.println("Mail sending is completed");
        }catch (Exception e){
            System.out.println("Error occured: "+e.getMessage());
        }
    }
}

SpringBootApplication Class

@SpringBootApplication
public class MailSenderApplication {

    @Autowired
    SendEmailService sendEmailService;

    public static void main(String[] args) {
        SpringApplication.run(MailSenderApplication.class, args);
    }

    @EventListener(ApplicationReadyEvent.class)
    public void triggerWhenStarts(){
        sendEmailService.sendEmail("mutlueren01@gmail.com","This e-mail has sending by Spring Boot","Spring Boot Mail Sender TEST");
    }
}
meren
  • 432
  • 5
  • 19

2 Answers2

0

You need to add SMTP certificate to java key store: How to import a .cer certificate into a java keystore?

or disable certificate check (not recommended): How to bypass ssl certificate checking in java

Kamil W
  • 2,230
  • 2
  • 21
  • 43
0

You can add your mail service provider as trusted:

spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com

This line should be added in application.properties file. Solution works for Java 11.

Falcon
  • 338
  • 3
  • 9