java使用微软exchange协议发送邮件时,若是HTTPS请求则默认使用apache HttpClient,当ssl证书验证不通过或域名不匹配则报错:HttpClient javax.net.ssl.SSLPeerUnverifiedException: Certificate doesn't match
解决方案:
构建自定义ExchangeService,忽略ssl证书验证和主机校验
自定义类CustomExchangeService继承 ExchangeService;重写protected Registry<ConnectionSocketFactory> createConnectionSocketFactoryRegistry()方法,修改EwsSSLProtocolSocketFactory为:
package com.service.emailService;
import microsoft.exchange.webservices.data.EWSConstants;
import microsoft.exchange.webservices.data.core.EwsSSLProtocolSocketFactory;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.request.HttpWebRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import javax.net.ssl.*;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
/**
* @author yanjl
* @ClassName CustomExchangeService
* @Description TODO
* @Date: 2025/3/28 15:04
*/
public class CustomExchangeService extends ExchangeService {
public CustomExchangeService(ExchangeVersion exchangeVersion) {
super(exchangeVersion);
}
@Override
protected Registry<ConnectionSocketFactory> createConnectionSocketFactoryRegistry() {
try {
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
public X509Certificate[] getAcceptedIssuers() { return null; }
};
return RegistryBuilder.<ConnectionSocketFactory>create()
.register(EWSConstants.HTTP_SCHEME, new PlainConnectionSocketFactory())
// 关键代码 :忽略ssl证书验证 和 主机名验证
.register(EWSConstants.HTTPS_SCHEME, EwsSSLProtocolSocketFactory.build(trustManager, (hostname, session) -> true))
.build();
} catch (GeneralSecurityException e) {
throw new RuntimeException(
"Could not initialize ConnectionSocketFactory instances for HttpClientConnectionManager", e
);
}
}
}