发送自动邮件时Could not connect to SMTP host: 10.1.1.195, port: 25;报错的解决方法

时间:2022-05-14 15:13:03

最近在测试公司内部系统自动发送邮件功能时,一直在报错:

javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException: Could not connect to SMTP host: 10.1.1.195, port: 25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at javax.mail.Transport.send0(Transport.java:219)
at javax.mail.Transport.send(Transport.java:81)
at com.gree.util.MailUtil.sendMessage(MailUtil.java:241)
at com.gree.util.MailUtil.sendTest(MailUtil.java:1112)
at com.gree.util.MailUtil.main(MailUtil.java:1120)</span>

在同事的电脑上同样的项目同样的代码都没问题,所以排除了服务器错误的问题,通过telnet测试端口也没问题,也可以ping通,最后发现原来是tomcat服务器缺少某些启动参数。。解决方法:在tomcat配置中加入该参数
Servers->双击Tomcat->Open launch configuration->Arguments->在VM arguments输入框最后添加下面这句:

-Djava.net.preferIPv4Stack=true</span>

然后在main函数开头添加下面这句:

System.setProperty("java.net.preferIPv4Stack", "true");</span>
再测试一下,果然不再报错,邮件顺利发送出去了~