Search code examples
javaemailtomcatjakarta-mail

Connection time out exception while sending mail through Java Mail API


        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true"); 
        props.put("mail.smtp.host", SMTPHost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587"); 
        Authenticator Auth= new MailAuthenticator();
        Session session = Session.getInstance(props, Auth);
        MimeMessage msg = new MimeMessage(session);
        //
        //
        Transport.send(msg);

The mail is sending successfully most of times but some times it is not sending and tomcat shows

        javax.mail.MessagingException: Could not connect to SMTP host: "SMTPHost - IP "     , port: 587;

nested exception is: java.net.ConnectException: Connection timed out: connect

This message appear every few hours in Tomcat logs.

javax.mail.MessagingException: Exception reading response; nested exception is: java.net.SocketException: Connection reset

    This message also appears rarely in a day.

any help really appreciated. Thanks.


Solution

  • There are 2 methods Transport.send() and Transport.sendMessage() available in the java mail API. You can read Difference between Transport methods send and sendMessage

    Try creating your own transport object and use sendMessage() for sending multiple messages.

    Using Transport.send() might be the reason why automated java mails are taking more time.

    If above is not the case, then problem is with the network.