Skip to content

Commit f6e765f

Browse files
wynnteoWynn Teo
andauthored
update BAEL-9355 (#18667)
Co-authored-by: Wynn Teo <[email protected]>
1 parent 69132ac commit f6e765f

File tree

1 file changed

+36
-0
lines changed
  • core-java-modules/core-java-networking/src/main/java/com/baeldung/mail

1 file changed

+36
-0
lines changed

core-java-modules/core-java-networking/src/main/java/com/baeldung/mail/EmailService.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,17 @@
22

33
import java.io.File;
44
import java.net.URI;
5+
import java.security.KeyManagementException;
6+
import java.security.NoSuchAlgorithmException;
7+
import java.security.cert.CertificateException;
8+
import java.security.cert.X509Certificate;
59
import java.util.Properties;
610

11+
import javax.net.ssl.SSLContext;
12+
import javax.net.ssl.SSLSocketFactory;
13+
import javax.net.ssl.TrustManager;
14+
import javax.net.ssl.X509TrustManager;
15+
716
import jakarta.mail.Authenticator;
817
import jakarta.mail.Message;
918
import jakarta.mail.Multipart;
@@ -40,6 +49,33 @@ public EmailService(String host, int port) {
4049
prop.put("mail.smtp.port", port);
4150
}
4251

52+
public EmailService(String host, int port, boolean bypassServerCertError) throws NoSuchAlgorithmException, KeyManagementException {
53+
prop = new Properties();
54+
prop.put("mail.smtp.host", host);
55+
prop.put("mail.smtp.port", port);
56+
if (bypassServerCertError) {
57+
58+
prop.put("mail.smtp.ssl.trust", "*");
59+
prop.put("mail.smtp.ssl.checkserveridentity", false);
60+
61+
// use this when SMTPS protocol
62+
// SSLContext sslContext = SSLContext.getInstance("TLS");
63+
// sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
64+
// SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
65+
// prop.put("mail.smtp.ssl.enable", "true");
66+
// prop.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
67+
// prop.put("mail.smtp.ssl.trust", "*");
68+
}
69+
}
70+
71+
TrustManager[] trustAllCerts = new TrustManager[] {
72+
new X509TrustManager() {
73+
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException{}
74+
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException{}
75+
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0];}
76+
}
77+
};
78+
4379
public static void main(String... args) {
4480
try {
4581
new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed").sendMail();

0 commit comments

Comments
 (0)