需求阐述
在写完定时任务发送邮件之后,调试的时候发现报错:Could not connect to SMTP host:smtp.exmail.qq.com,port:465。一开始我以为是在for循环里发送邮件导致的,把循环禁用掉之后,发现还是这个报错。说明不是for循环的问题。之前定时任务发送邮件没问题,只有我写的这个定时任务循环发送邮件报这个错。
解决方式
在设置发送邮件的邮件服务器的属性时,添加这样一行代码:
props.put(“mail.smtp.ssl.protocols”, “TLSv1.2”);
public getEmailSession(final String host, final String port, final String username, final String password) {
this.host = host;
this.username = username;
this.password = password;
this.port = port;
Properties props = null;
props = new Properties();
// 设置发送邮件的邮件服务器的属性
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", port);
props.put("mail.smtp.ssl.enable", "true");
**props.put("mail.smtp.ssl.protocols", "TLSv1.2");**
session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}