JAVA Mail和Office 365在连接时挂起
我们有一个应用程序,它严重依赖JAVA Mail发送电子邮件。我们已根据以下设置连接超时属性(从长值设置,是否需要整数才能生效?) 一段时间后,应用程序会暂停,并且永远不会从Office 365 smtp帐户恢复(仅在Office 365中发生)。我们在JAVA mail中启用了调试模式,失败的代码行如下:JAVA Mail和Office 365在连接时挂起,java,office365,jakarta-mail,Java,Office365,Jakarta Mail,我们有一个应用程序,它严重依赖JAVA Mail发送电子邮件。我们已根据以下设置连接超时属性(从长值设置,是否需要整数才能生效?) 一段时间后,应用程序会暂停,并且永远不会从Office 365 smtp帐户恢复(仅在Office 365中发生)。我们在JAVA mail中启用了调试模式,失败的代码行如下: DEBUG: setDebug: JavaMail version 1.4.5 DEBUG: getProvider() returning javax.mail.Provider[TRAN
DEBUG: setDebug: JavaMail version 1.4.5
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp-mail.outlook.com", port 587, isSSL false
当达到此点时,套接字超时似乎不起作用,应用程序将暂停。下面是一个无限循环,它一直连接到邮件服务器,然后最终被卡住
public static void main(String[] args){
String smtpServer = "smtp-mail.outlook.com";
String username = "test@domain.com";
String password = "password";
int portNumber = 587;
Long socketTimeout = 10000L;
Properties props = new Properties();
props.put("mail.smtp.ssl.trust", "*");
props.put("mail.smtp.host", "smtp-mail.outlook.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", portNumber);
props.put("mail.smtp.timeout", socketTimeout);
props.put("mail.smtp.connectiontimeout", socketTimeout);
props.put("mail.smtp.starttls.enable", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
while(true){
Session sess = Session.getInstance(props, authenticator);
sess.setDebug(true);
try {
Transport t = sess.getTransport("smtp");
t.connect(smtpServer, portNumber, username, password);
t.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
如果你读了,上面写着:
SMTP协议提供程序支持以下属性,这些属性
可以在JavaMail会话对象中设置。属性始终是
设置为字符串;“类型”列描述字符串的显示方式
解释。例如,使用
props.put("mail.smtp.port", "888");
设置mail.smtp.port属性,该属性的类型为int
属性实际上应该是字符串,但较新版本的JavaMail也将接受它们作为整数,而不是长字符串
另外,请注意,由于您将用户名和密码直接传递给connect方法,因此您可以这样做。您不需要为主机和端口设置属性,因为您也直接传递它们
props.put("mail.smtp.port", "888");