解决 Gmail 邮件发送 Java 程序中的 javax.net.ssl 错误
- javax.net.ssl 错误通常是由于 SSL 证书不受信任或服务器端配置不正确引起的。建议的代码是使用 JavaMail 库中的 SSLUtils 类,通过设置信任的 SSL 证书来解决此问题。示例代码如下:
import javax.net.ssl.*;
public class SSLUtils {
public static void trustAllHostnames() {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
return true;
}});
}
public static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new TrustAllManager();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance('SSL');
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
private static class TrustAllManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
}
在发送邮件前,调用 SSLUtils.trustAllHostnames() 和 SSLUtils.trustAllHttpsCertificates() 方法即可。这样做会使程序信任所有 SSL 证书,包括不受信任的证书,因此需要谨慎使用。
- 如果网站使用的是 HTTPS,就证明 SSL 已经启用了。如果 SSL 证书不受信任,那么浏览器会提示'不安全连接'等警告信息。如果你想确定网站使用的 SSL 证书是否受信任,可以在浏览器中打开该网站,然后查看浏览器地址栏中的锁形状以及 HTTPS 字样。如果锁是绿色的,说明网站使用的是受信任的 SSL 证书。如果锁是红色的,或者浏览器提示该网站的证书不受信任,那么该网站使用的就是非受信任的 SSL 证书。
原文地址: https://www.cveoy.top/t/topic/nOv1 著作权归作者所有。请勿转载和采集!