尝试通过TLS连接邮件服务器与证书,但连接成功,即使我放错了证书。 我添加了这些属性:
javaMailProperties.put("mail.smtp.auth",true);
javaMailProperties.setProperty("mail.smtp.timeout", "8500");
javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
javaMailProperties.put("mail.smtp.socketFactory", sslSocketFactory);
javaMailProperties.put("mail.smtp.socketFactory.fallback", true);
我创建套接字工厂的方式: (我使用服务器上的公共certifucate创建了新的密钥库。并创建了socketfctory)
private MailSSLSocketFactory getMailSSLSocketFactory(String certificate){
try {
logger.debug("Start, getting mail ssl socket factory");
KeyStore keyStore = getKeyStore(certificate);
KeyManager[] keyManagers = getKeyManagers(keyStore);
TrustManager[] trustManagers = getTrustManagers(keyStore);
MailSSLSocketFactory sslSocketFactory = getMailSSLSocketFactory(keyManagers, trustManagers);
logger.debug("End, getting mail ssl socket factory");
return sslSocketFactory;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private KeyStore getKeyStore(String certificate) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
InputStream certificateStream = new ByteArrayInputStream(certificate.getBytes(StandardCharsets.UTF_8));
X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(certificateStream);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("smtp.certificate", x509Certificate);
return keyStore;
}
private KeyManager[] getKeyManagers(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, null);
return keyManagerFactory.getKeyManagers();
}
private TrustManager[] getTrustManagers(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
return trustManagerFactory.getTrustManagers();
}
private MailSSLSocketFactory getMailSSLSocketFactory(KeyManager[] keyManagers, TrustManager[] trustManagers) throws GeneralSecurityException {
MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
sslSocketFactory.setKeyManagers(keyManagers);
sslSocketFactory.setTrustManagers(trustManagers);
return sslSocketFactory;
}
我错过了什么或错了什么?