为什么JavaMail连接超时太长

kub*_*a44 17 java jakarta-mail connection-timeout

在我的应用程序中,我连接到服务器以验证用户.这是代码:

try {
        Properties prop = new Properties();
        prop.put("mail.smtp.starttls.enable","true");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.connectiontimeout", 1000);


        Session session = Session.getInstance(prop, null);
        Transport transport = session.getTransport("smtp");
        transport.connect("mion.elka.pw.edu.pl", 587, registerLog, registerPass);
        transport.close();
        return true;
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch(AuthenticationFailedException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (MessagingException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
Run Code Online (Sandbox Code Playgroud)

我将连接超时设置为1000毫秒= 1秒,但它被忽略.当我调试并设置错误的用户名和密码时,我抓住了

javax.mail.MessagingException: java.net.SocketTimeoutException: Read timed out
Run Code Online (Sandbox Code Playgroud)

不是在1000毫秒之后,而是在5000*60毫秒= 5分钟之后

怎么了 ?我怎样才能减少时间?

Sha*_*med 17

您也可以设置套接字I/O超时.当它连接但无法从服务器读取数据时,它将继续等待.

prop.put("mail.smtp.timeout", 1000);
Run Code Online (Sandbox Code Playgroud)

读取超时表示您已连接但无法从服务器读取数据.

  • 您正在使用相当旧版本的JavaMail.设置超时属性时,请尝试使用字符串而不是整数.旧版本的JavaMail只能正确处理字符串. (2认同)

J. *_*now 9

由于您使用的是SSL,因此可以尝试配置smtps命名空间,而不是smtp:

prop.put("mail.smtps.timeout", 1000);
prop.put("mail.smtps.connectiontimeout", 1000);
Run Code Online (Sandbox Code Playgroud)

BTW:属性中的超时值既可以传递int,也可以传递String.JavaMail将正确处理它们(至少v1.5 +).


小智 8

我有同样的问题.它使用String而不是整数.

prop.put("mail.smtp.timeout", "1000");    
prop.put("mail.smtp.connectiontimeout", "1000");    
Run Code Online (Sandbox Code Playgroud)

  • 根据 [the JavaDocs](https://javaee.github.io/javamail/docs/api//com/sun/mail/smtp/package-summary.html):SMTP 协议提供程序支持以下属性,这些属性可能在 JavaMail `Session` 对象中设置。**属性总是设置为字符串**;Type 列描述了如何解释字符串。 (2认同)

小智 8

mail.smtp.connectiontimeout
类型:int
描述:套接字连接超时值(以毫秒为单位)。这个超时是由java.net.Socket实现的。默认为无限超时。

mail.smtp.timeout 类型:int
描述:套接字读取超时值(以毫秒为单位)。这个超时是由java.net.Socket实现的。默认为无限超时。

mail.smtp.writetimeout 类型:int
描述:套接字写入超时值(以毫秒为单位)。此超时是通过每个连接使用 java.util.concurrent.ScheduledExecutorService 来实现的,该服务会调度一个线程在超时到期时关闭套接字。因此,使用此超时的开销是每个连接一个线程。默认为无限超时。


小智 5

不,这只是因为值必须是字符串"1000"而不是整数1000


kub*_*a44 1

我通过更改为最新版本的 JavaMail(JavaMail 1.5)解决了我的问题。我在那里写到:http://openejb.979440.n4.nabble.com/Which-version-of-JavaMail-td4665285.html

感谢大家的帮助,特别是 Bill Shannon :)