调用内部邮件服务器发送邮件,unable to find valid certification path to requested target
时间: 2023-11-06 18:03:12 浏览: 87
调用内部邮件服务器发送邮件时出现"unable to find valid certification path to requested target"的错误是因为本地没有目标服务器的证书。这个问题可以通过以下两种方法来解决:
方法一是在运行Java环境中安装目标服务器的证书。你可以使用keytool命令生成目标服务器证书的cer格式文件,并将其添加到Java证书库中。
方法二是在建立连接时跳过证书验证。你可以使用Apache HttpClient库来创建一个支持跳过证书验证的httpClient对象。
代码示例:
```
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MailSender {
public static void main(String[] args) {
CloseableHttpClient httpClient = getSslHttpClient();
// 使用httpClient发送邮件的代码...
}
public static CloseableHttpClient getSslHttpClient() {
SSLContext sslContext = null;
try {
sslContext = SSLContextBuilder.create()
.loadTrustMaterial((x509Certificates, s) -> true)
.build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
}
}
```
阅读全文