I am trying to send an email using the following code:

try { String mailFrom = "sender@mail.ru"; String pass = "pass"; String mailTo = "recipient@gmail.com"; java.util.Properties props = new Properties(); props.put("mail.smtp.host", "smtp.mail.ru"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.connectiontimeout", "60000"); // 60 seconds props.put("mail.smtp.timeout", "60000"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(mailFrom, pass)); } }); Message msg = new MimeMessage(session); InternetAddress addressFrom = new InternetAddress(mailFrom); msg.setFrom(addressFrom); InternetAddress addressTo = new InternetAddress(mailTo); msg.setRecipient(Message.RecipientType.TO, addressTo); msg.setSubject("testemail"); Transport.send(msg); } catch (Throwable e) { System.err.println("Exception : " + e.toString()); } 

but I get the error:

Exception: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.

At the same time, I added the mail.ru ssl certificate to the JVM certificate store, and it was successfully added.

If I add the following property to the session:

 props.put("mail.smtp.ssl.trust", "*"); 

then after a minute (after the set timeout), I get another error:

Exception: javax.mail.MessagingException: Exception reading response; nested exception is: java.net.SocketTimeoutException: Read timed out

How to fix it and still send email?

    1 answer 1

    The problem was that I tried to send an empty message, without a body (the email client usually allows you to send such messages, but in my case this led to an error).

    This became clear after I added a property to the session.

    props.put("mail.debug", "true");

    After that, in the debug information, I saw the reason for the error:

    354 Enter message, ending with "." on a line by itself

    DEBUG SMTP: MessagingException while sending, THROW:

    javax.mail.MessagingException: No MimeMessage content

    After receiving this error description, I added the message body:

     msg.setText("Test message!"); 

    and email was successfully sent.