在ssh中使用javamail自動發送郵件,出現異常如下
javax.mail.MessagingException: Could not connect to SMTP host: xxx.xxx.xxx, port: 25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
這裏使用的smtp服務器是公司內部的服務器,之前使用163的smtp服務器時沒有出現該問題,查了很長時間的資料,終於找到解決方法:
將java.net.preferIPv4Stack設置爲true,如果程序中有main方法,可以在main方法的開頭加入
System.setProperty("java.net.preferIPv4Stack", "true");
如果使用tomcat服務器,則可以給tomcat加上啓動參數
-Djava.net.preferIPv4Stack=true
如果是使用的eclipse javaee啓動的tomcat,使用如下方法設置:
切換到Servers選項卡,雙擊Tomcat,在General Information中找到open launch configuration並單擊
在彈出的窗口中選擇第二個選項卡Arguments,在VM arguments的輸入框的最後加上
-Djava.net.preferIPv4Stack=true