JavaMail error + Unrecognized SSL message, plaintext connection? - jakarta-mail

Using below code to read mails from a Zimbra mail server.
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.auth", "true");
pop3Props.setProperty("mail.pop3.port", "110");
pop3Props.setProperty("mail.pop3.socketFactory.port", "110");
URLName url = new URLName("pop3", host, 110, "",username, password);
Session session = Session.getInstance(pop3Props, null);
Store store = new POP3SSLStore(session, url);
store.connect();
But keep getting this error
javax.mail.MessagingException: Connect failed;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:148)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at VerifyMail.readPOP3(VerifyMail.java:177)
at VerifyMail.main(VerifyMail.java:20)
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at java.io.DataInputStream.readLine(Unknown Source)
at com.sun.mail.pop3.Protocol.simpleCommand(Protocol.java:347)
at com.sun.mail.pop3.Protocol.<init>(Protocol.java:91)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:201)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:144)
... 5 more
Can anyone help on how to resolve this?

Read this list of common mistakes and then clean up your code.
The Gmail example should work for you as well, although obviously you'll need to change the host name.

This will help you bypass certificate process and get directly to ssl host
MailSSLSocketFactory sf = null;
try
{
sf = new MailSSLSocketFactory();
}
catch (GeneralSecurityException e)
{
e.printStackTrace();
}
sf.setTrustAllHosts(true);
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.ssl.enable", "true");
pop3Props.setProperty("mail.protocol.ssl.trust", "pop3.live.com");
pop3Props.put("mail.pop3s.ssl.socketFactory", sf);
pop3Props.setProperty("mail.pop3s.port", "995");
Session session = Session.getInstance(pop3Props);
try
{
/* Get a Store object*/
Store store = session.getStore("pop3s");
//process further activity
}

Related

Not able to get access token from azure AD using MSAL4J

I'm trying to access graph api. I'm using MSAL4J to access the graph apis. But I'm getting com.microsoft.aad.msal4j.MsalClientException: java.net.SocketTimeoutException: connect timed out even when I'm not using my vpn.
I'm following this tutorial. I've followed all the steps mentioned in there.
Here the stack trace:
Exception in thread "main" java.util.concurrent.ExecutionException: com.microsoft.aad.msal4j.MsalClientException: java.net.SocketTimeoutException: connect timed out at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357) at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) at ClientCredentialGrant.getAccessTokenByClientCredentialGrant(ClientCredentialGrant.java:78) at ClientCredentialGrant.main(ClientCredentialGrant.java:36) Caused by: com.microsoft.aad.msal4j.MsalClientException: java.net.SocketTimeoutException: connect timed out at com.microsoft.aad.msal4j.HttpHelper.executeHttpRequest(HttpHelper.java:53) at com.microsoft.aad.msal4j.AadInstanceDiscoveryProvider.executeRequest(AadInstanceDiscoveryProvider.java:218) at com.microsoft.aad.msal4j.AadInstanceDiscoveryProvider.sendInstanceDiscoveryRequest(AadInstanceDiscoveryProvider.java:172) at com.microsoft.aad.msal4j.AadInstanceDiscoveryProvider.doInstanceDiscoveryAndCache(AadInstanceDiscoveryProvider.java:271) at com.microsoft.aad.msal4j.AadInstanceDiscoveryProvider.getMetadataEntry(AadInstanceDiscoveryProvider.java:56) at com.microsoft.aad.msal4j.AuthenticationResultSupplier.getAuthorityWithPrefNetworkHost(AuthenticationResultSupplier.java:32) at com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier.execute(AcquireTokenByAuthorizationGrantSupplier.java:59) at com.microsoft.aad.msal4j.AcquireTokenByClientCredentialSupplier.acquireTokenByClientCredential(AcquireTokenByClientCredentialSupplier.java:63) at com.microsoft.aad.msal4j.AcquireTokenByClientCredentialSupplier.execute(AcquireTokenByClientCredentialSupplier.java:49) at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:59) at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:17) at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590) at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1582) at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056) at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157) Caused by: java.net.SocketTimeoutException: connect timed out at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:673) at sun.net.NetworkClient.doConnect(NetworkClient.java:175) at sun.net.www.http.HttpClient.openServer(HttpClient.java:463) at sun.net.www.http.HttpClient.openServer(HttpClient.java:558) at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264) at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1138) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1032) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177) at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1546) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474) at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338) at com.microsoft.aad.msal4j.DefaultHttpClient.readResponseFromConnection(DefaultHttpClient.java:107) at com.microsoft.aad.msal4j.DefaultHttpClient.executeHttpGet(DefaultHttpClient.java:47) at com.microsoft.aad.msal4j.DefaultHttpClient.send(DefaultHttpClient.java:35) at com.microsoft.aad.msal4j.HttpHelper.executeHttpRequestWithRetries(HttpHelper.java:96) at com.microsoft.aad.msal4j.HttpHelper.executeHttpRequest(HttpHelper.java:49) ... 16 more
Any help will be appreciated.
Finally, I figured it out. And writing this answer with hope that it will help someone. com.microsoft.aad.msal4j.MsalClientException: java.net.SocketTimeoutException: connect timed out This exception was occurring due to the proxy issues.
My system was behind the proxy so it was not able to connect with microsoftonline servers.
I have two approaches to get the access_token from azure AD.
First Approach
Using REST API provided by AZURE AD
public String getAccessToken() throws UnsupportedOperationException, IOException {
ObjectMapper mapper = new ObjectMapper();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("your_proxy_address", your_proxy_port));
OkHttpClient client = new OkHttpClient.Builder().proxy(proxy).build();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(
"grant_type=client_credentials&client_id=your_client_id&scope=https://graph.microsoft.com/.default&client_secret=your_client_secret",
mediaType);
Request request = new Request.Builder()
.url("https://login.microsoftonline.com/your tenent id/oauth2/v2.0/token")
.method("POST", body).addHeader("Content-Type", "application/x-www-form-urlencoded").build();
Response response = client.newCall(request).execute();
// String token = response.body().string();
return mapper.readTree(response.body().string()).get("access_token").asText();
}
You can get the access_token by using this method. Another approach is, by using the MSAL4J library.
Second approach
First build client object
private static void BuildConfidentialClientObject() throws Exception {
Proxy proxy = AuthProvider.getInstance().getProxy();
app = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(secret))
.proxy(proxy).authority(authority).build();
}
Then get the access_token
private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters
.builder(Collections.singleton(scope)).build();
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
return future.join();
}
Now you can access the graph APIs using this access_token and complete your tasks.
PS: I'm using demon approach for my tasks. There are different approaches to fulfill your requirements.
You can have a look here for authentication approach reference.

webBrowser component throws exception occasionally codenameone

I used WebBrowser component to view the url that occasionally throws following exception and the webBrowser is not displayed if there is an exception. What is the issue here? My code is at the end. thanks
Received exception: Unknown host
java.lang.Throwable: Unknown host
at javafx.scene.web.WebEngine$LoadWorker.describeError(WebEngine.java:1402)
at javafx.scene.web.WebEngine$LoadWorker.dispatchLoadEvent(WebEngine.java:1341)
at javafx.scene.web.WebEngine$LoadWorker.access$1100(WebEngine.java:1219)
at javafx.scene.web.WebEngine$PageLoadListener.dispatchLoadEvent(WebEngine.java:1206)
at com.sun.webkit.WebPage.fireLoadEvent(WebPage.java:2387)
at com.sun.webkit.WebPage.fwkFireLoadEvent(WebPage.java:2231)
at com.sun.webkit.network.URLLoader.twkDidFail(Native Method)
at com.sun.webkit.network.URLLoader.notifyDidFail(URLLoader.java:843)
at com.sun.webkit.network.URLLoader.lambda$didFail$93(URLLoader.java:826)
at com.sun.webkit.network.URLLoader$$Lambda$168/1472224915.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$164(PlatformImpl.java:292)
at com.sun.javafx.application.PlatformImpl$$Lambda$64/2085765319.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(PlatformImpl.java:291)
at com.sun.javafx.application.PlatformImpl$$Lambda$63/817822539.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$55/1412924864.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
My code:
InfiniteProgress ip = new InfiniteProgress();
f.addComponent(BorderLayout.NORTH, ip);
WebBrowser view = new WebBrowser() {
#Override
public void onStart(String url) {
System.out.println("del ip");
f.removeComponent(ip);
}
};
view.setURL("https://docs.google.com/gview?embedded=true&url=" + pdfUrlSelected);
f.addComponent(BorderLayout.CENTER, view);
f.revalidate();
That generally means your web connection or DNS is problematic.
If the host isn't found networking can't really proceed.

Sending passive checks to the Nagios NSCA add-on from JAVA Application

I've implemented JSend NSCA to send passive checks to Nagios like below:
public static void main(String[] args) {
NagiosSettings nagiosSettings = new NagiosSettingsBuilder()
.withNagiosHost("192.168.1.20")
.withPassword("nagiosadmin")
.withPort(5666)
.withConnectionTimeout(5000)
.withResponseTimeout(15000)
.create();
NagiosPassiveCheckSender sender = new NagiosPassiveCheckSender(
nagiosSettings);
MessagePayload payload = new MessagePayloadBuilder()
.withHostname("localhost")
.withLevel(Level.CRITICAL)
.withServiceName("Test Service Name")
.withMessage("Test Message")
.create();
try {
sender.send(payload);
} catch (NagiosException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
But I had the following errors:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at com.googlecode.jsendnsca.core.NagiosPassiveCheckSender.send(NagiosPassiveCheckSender.java:69)
at app.QuickStart.main(QuickStart.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Nagios Username and password are: nagiosadmin/nagiosadmin.
The IPserver for nagios is 192.168.1.20.
Thank you.
Can you try a quick telnet test
From your command line run
telnet 192.168.1.20 5666
If the response is
Connecting To 192.168.1.20...Could not open connection to the host, on port 5666: Connect failed
Then the NSCA daemon is either
not running
running on a different port other than 5666
BTW, Im the project lead for jsendnsca. In future, you can post questions like this at
https://code.google.com/p/jsendnsca/issues/list
and create an issue

Java mail: Could not connect to SMTP host: ..., port: ..., java.net.ConnectException: Operation timed out

Thanks in advance to any help with this. Java Mail always worked for me but now it's throwing this annoying Exception:
//Exception:
run:
DEBUG: setDebug: JavaMail version 1.4.6
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "xxxxxx", port 25, isSSL false
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: xxxxxx, port: 25;
nested exception is:
java.net.ConnectException: Operation timed out
at vesso.mail.TestMail.sendMail(TestMail.java:79)
at vesso.mail.TestMail.main(TestMail.java:26)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: mail.mentorlicitacao.com.br, port: 25;
nested exception is:
java.net.ConnectException: Operation timed out
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1962)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
at vesso.mail.TestMail.sendMail(TestMail.java:71)
... 1 more
Caused by: java.net.ConnectException: Operation timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1928)
... 4 more
Java Result: 1
BUILD SUCCESSFUL (total time: 1 minute 19 seconds)
I've tried to connect with Mail.app (using MacOS), and it worked fine.
//Code:
final String host = "xxxx";
final int port = 25;
final String username = "xxxx";
final String password = "xxxx";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(username));
message.setSubject("Teste");
message.setText("Bla, Bla, Bla!");
Transport transport = session.getTransport("smtp");
transport.connect (host, port, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
Thanks!
Problem solved by changing the port from 25 to 587. The conclusion I have reached is that my ISP blocks this port.
Thanks everyone.

javax.mail.MessagingException: Connection reset while trying to access gmail using java mail API

I was trying to read through the mails in my gmail account using java mail API. This is the code:
import java.util.*;
import java.io.*;
import java.awt.*;
import javax.mail.*;
import javax.mail.search.FlagTerm;
import javax.mail.Flags.Flag;
public class MailPharser {
/**
* #param args
*/
public void mailRead()
{
Folder inbox;
// TODO Auto-generated method stub
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com","<mailid#gmail.com>", "<password>");
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
}
catch (Exception ex)
{ System.out.println("Error caught"); ex.printStackTrace(); }
}
public static void main(String[] args) {
MailPharser mp = new MailPharser();
mp.mailRead();
}
}
While running, i am getting the below error:
javax.mail.MessagingException: Connection reset;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at MailPharser.mailRead(MailPharser.java:26)
at MailPharser.main(MailPharser.java:40)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:113)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:111)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:637)
... 4 more
I added trace and see that the connect call is failing. Am i doing anything wrong? any help would do. thanks in advance...
It's probably a network problem unrelated to JavaMail, e.g., a proxy or firewall between you and Gmail.
If you want to find out whether it's your code that's broken or the network that's broken, you can test using the code that comes with JavaMail. If the JavaMail code works, then you know there's something wrong with your code, and you can use the JavaMail code in the FAQ to improve your code.
If you discover that it's a network problem, the JavaMail FAQ also has tips for debugging it further.

Resources