Hutool 线上邮件发送错误问题
测试环境,拿163邮箱来测试,是正常成功。但是,部署到生产环境时,是一个内网邮件系统。配置好生产的对应smtp服务器地址以及账号密码后,提示如下
Could not connect to SMTP host: ***.***.com, port: 465
我把 hutool 做了封装,核心代码
@AutoConfiguration
@EnableConfigurationProperties(MailProperties.class)
public class MailConfig {
@Bean
@ConditionalOnProperty(value = "mail.enabled", havingValue = "true")
public MailAccount mailAccount(MailProperties mailProperties) {
MailAccount account = new MailAccount();
account.setHost(mailProperties.getHost());
account.setPort(mailProperties.getPort());
account.setAuth(mailProperties.getAuth());
account.setFrom(mailProperties.getFrom());
account.setUser(mailProperties.getUser());
account.setPass(mailProperties.getPass());
account.setSocketFactoryPort(mailProperties.getPort());
account.setStarttlsEnable(mailProperties.getStarttlsEnable());
account.setSslEnable(mailProperties.getSslEnable());
account.setTimeout(mailProperties.getTimeout());
account.setConnectionTimeout(mailProperties.getConnectionTimeout());
return account;
}
}
确定自己配置没有问题。网上的解决按方案如下:
1.修改jdk协议(无效)
网上说,是jdk1.8版本导致SSL调用权限上有问题,版本比较高。解决方法是:
找到jdk 1.8安装目录,找到C:\Program Files\Java\jre里面的lib\security 下面有个java.security。找到对应的 SSLv3,删除掉,重启项目就好了。(删掉SSLv3就是允许SSL调用)
2.修改代码,添加协议(无效)
网上说是代码里添加协议:props.put("mail.smtp.ssl.protocols", "TLSv1.2");
转换到hutool,如下:
account.setSslProtocols("TLSv1.2");
3.最终解决办法
网上办法
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(props);
转换到 hutool,如下:
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
account.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
最终代码
@AutoConfiguration
@EnableConfigurationProperties(MailProperties.class)
public class MailConfig {
@Bean
@ConditionalOnProperty(value = "mail.enabled", havingValue = "true")
public MailAccount mailAccount(MailProperties mailProperties) {
MailAccount account = new MailAccount();
account.setHost(mailProperties.getHost());
account.setPort(mailProperties.getPort());
account.setAuth(mailProperties.getAuth());
account.setFrom(mailProperties.getFrom());
account.setUser(mailProperties.getUser());
account.setPass(mailProperties.getPass());
account.setSocketFactoryPort(mailProperties.getPort());
account.setStarttlsEnable(mailProperties.getStarttlsEnable());
account.setSslEnable(mailProperties.getSslEnable());
account.setTimeout(mailProperties.getTimeout());
account.setConnectionTimeout(mailProperties.getConnectionTimeout());
try {
// 解决连接smtp服务失败问题
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
account.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
return account;
}
}
参考链接:线上发送邮件问题记录