Search code examples
javajakarta-mailconnection-timeout

JavaMail connection timeout is not working as per properties


Javax mail version used 1.6.2

manually setting JavaMailSender

Timeout thing I tried with mail.smtp.timeout & mail.smtps.timeout.
And, I tried with both String & Integer value 3000.

    String timeOut = "3000";
    Properties pros = new Properties();
    pros.put("mail.smtp.timeout", timeOut);
    pros.put("mail.smtp.connectiontimeout", timeOut);
    pros.put("mail.smtp.writetimeout", timeOut);

    pros.put("mail.smtp.auth", "true");
    pros.put("mail.smtp.starttls.enable", "true");


    jmailSender.setJavaMailProperties(pros);

    return jmailSender;

It's taking around 7 seconds without any fail. Since by default is infinite, so most probably it is not setting somehow

Are any properties missing or something else?


Solution

  • The properties mail.smtp.connectiontimeout and mail.smtps.connectiontimeout only apply while establishing the connection. It is not related to any timeouts during transport.

    The properties mail.smtp.timeout and mail.smtps.timeout are related to the time blocked waiting for a read. This is related to reading SMTP response codes.

    The properties mail.smtp.writetimeout and mail.smtps.writetimeout are related to writing chunks of data which can vary in size.

    None of these timeouts represent a deadline for a single transaction of sending a mime message. What is happening is that there is no single action (connect, read, write) that is exceeding the 3000ms.

    For example, connect could take 1000ms, followed by say 30 requests (write) and response parsing (reads) that take 100ms, and set of say 3 writes to send the message that take 1000ms each due to the speed of the network and size of the message. That is 1000 + (30 * 100) + (3 * 1000) = 7000ms total time but no single action exceeded the timeouts.

    In a test environment

    1. Set all timeouts to 3000.
    2. Set connectimeout to 1 and test. You should see the connection fail.
    3. Restart the test by setting it back to 3000 and set timeout to 1. You should see the reads fail.
    4. Restart the test by setting it back to 3000 and set writetimeout to 1. You should see the transport fail.

    If the test doesn't act this way you either haven't set the properties correctly (typo or smtp vs. smtps). Or you are really lucky to have such low latency.