Can't receive mail from POP3 GMAIL by using Javamail, get SSLHandshakeException - java

I have JAVA application which work as service on Tomcat server. I need to develope service for receiving mail from GMAIL pop3 server. I use Javamail. I have written usual code, but when I deploy it on server I am getting
javax.mail.MessagingException: Connect failed;
nested exception is:
javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
As for development my Tomcat started on Localhost.
And this problemm looks like concerned with certificate.
My code is
public void downloadMail() {
try {
// connects to the message store and opens the inbox folder
Store store = session.getStore(protocol);
store.connect(username, password);
Folder folderInbox = store.getFolder(inbox);
folderInbox.open(Folder.READ_WRITE);
// fetches new messages from server
Message[] messages = folderInbox.getMessages();
for (int i = 0; i < messages.length; i++) {
Mail mail = extractMail(messages[i]);
messages[i].setFlag(Flags.Flag.DELETED, true);
}
// disconnect
folderInbox.close(false);
store.close();
} catch (NoSuchProviderException ex) {
System.out.println( "No provider for pop3.");
ex.printStackTrace();
} catch (MessagingException ex) {
System.out.println( "Could not connect to the message store");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println( "Can not save file or open directory");
ex.printStackTrace();
}
}
I am getting exception on line store.connect(username, password);
I use properties:
mail.pop3.host=pop.gmail.com
mail.pop3.port=995
mail.pop3.ssl.enable=true
mail.pop3.protocol=pop3
mail.pop3.inbox=INBOX
Please help me to solve this problem. I never worked with Tomcat and certificates before!

Related

Unable to connect to Oracle database using the JAR file

I'm using eclipse 2020 edition and I've added all libraries I need to connect to Oracle server like ojdbc7.jar and my code is like this:
public Connection SetDatabaseConnection() {
writeInLog("Connecting to IRB", 0);
if(openConnection()){
try {
productionPool.setDriverType("thin");
productionPool.setUser(username);
productionPool.setPassword(password);
productionPool.setPortNumber(Integer.parseInt(port));
productionPool.setServerName(IP);
productionPool.setServiceName(serviceName);
productionPool.setURL("jdbc:oracle:thin:#"+ _connStr.substring(_connStr.indexOf(":")+1));
productionPooledConnection = productionPool.getPooledConnection();
if (productionPooledConnection != null) {
//return true;
currentConnection = productionPooledConnection.getConnection();
logger.info("Connected to IRB server");
return currentConnection;
}
} catch (SQLException ex) {
logger.info("Unable to connect to IRB server, SQLException: "+ex.getMessage());
System.out.println(" (IRB-Exception) DB Exception: \n"+ ex);
}
}
}
my problem is: i can connect to the server while debugging or running the application in the eclipse but when I exported a JAR file the application stopped in this step.
in addition:
my code to open a connection:
private boolean openConnection(){
try {
productionPool = new OracleConnectionPoolDataSource();
productionPooledConnection = new OraclePooledConnection();
logger.info("openConnection(): Connected to IRB server \n");
return true;
} catch (SQLException e) {
e.printStackTrace();
logger.info("Unable to connect to IRB server , SQLException: "+e.getMessage());
}
logger.info("openConnection(): Unable to connect to IRB server \n");
return false;
}
The application never throws any excption it only write in the log file this statment: writeInLog("Connecting to IRB", 0);
I couldn't find the exact reason why this happened but I removed the JARs that cause the error FAT Jar Export: couldn't find the class-path for ...etc and import them again. It worked successfully.

can't connect with pop3 server

i want to check my mails with an app. my code so far:
my provider uses SSL, see
here.
my code so far:
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3s.host", "pop.1und1.de");
properties.put("mail.pop3s.port", "995");
Session emailSession = Session.getDefaultInstance(properties);
//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore("pop3s");
emailStore.connect(<myMailAdress>, <password>);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for(Message message:messages) {
String from = message.getFrom()[0].toString().toLowerCase();
Log.e("XXXXXX",from);
}
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
the code runs until emailStore.connect(). There i get the Exception
javax.mail.MessagingException: Connect failed; nested exception is: javax.net.ssl.SSLHandshakeException: Connection closed by peer.

Connect to local POP3 inbox Java

I am trying to connect to locally hosted email POP3 inbox and display emails in the mailbox, but I keep getting error:
Exception in thread "main" javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at com.kami.utils.MailClient.checkInbox(MailClient.java:33)
at com.kami.Main.main(Main.java:38)
My class looks like this:
public class MailClient {
private String host;
private String username;
private String password;
private String provider;
protected Session session;
public MailClient() {
Properties props = new Properties();
this.host = "localhost";
this.username = "unix-user";
this.password = "unix-password";
this.provider = "pop3";
this.session = Session.getDefaultInstance(props, null);
}
public void checkInbox() throws MessagingException, IOException {
Store store = session.getStore(provider);
store.connect(host, username, password); //This is line 33
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for(Message message : messages){
System.out.println(message.getReceivedDate());
System.out.println(message.getSubject());
}
inbox.close(true);
store.close();
}
}
It is locally hosted email server using Dovecot IMAP/POP3 Server Version 2.2.9 and Postfix Mail Server Postfix version 2.11.0
First telnet 110 port in your machine to check if the service is running there. In my laptop i don't have a pop3 server running, and this is the result:
hans#andes:~$ telnet localhost 110
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
If the connection succeed, follow the protocol authentication of pop3 with your own data:
hans#andes:~$ telnet mail.foo.com 110
Trying X.X.X.X...
Connected to mail.foo.com.
Escape character is '^]'.
+OK mail.foo.com POP3 server ready
user fooUser
+OK hello fooUser, please enter your password
pass fooPassword
+OK server ready
In your case telnet localhost; note too that you only should issue the commands: telnet, user and pass. The rest is the response from the server.
If all this works, the problem is on something with your java configuration, check the documentation and samples from the library.
The below method will fetch messages from a pop mailbox (given _Host=localhost, _User=unix-user, _Password=unix-password, _Protocol="pop3"). However you must be sure of a few things:
1) "localhost" is running a "pop3" server and not a "pop3s" (secure protocol) server;
2) the "pop3" server on "localhost" is listening on the default port
3) "unix-user" has a pop3 mailbox
Based on your follow-up, it seems like you are expecting to be able to send mail from the pop3 account. This is not how it works as pop3 is only a way to retrieve messages, not send them. To send mail, you need to establish a separate connection to an SMTP server.
public Message[] getMessages(int maxCount)
throws MessagingException
{
// Get a Session object
Properties props = new Properties();
Session session = Session.getInstance(props);
// Get a Store object
Store store = session.getStore(_protocol);
// Connect
store.connect(_host,_user,_password);
// Open a Folder
Folder folder = store.getFolder(_mailbox);
if (folder == null || !folder.exists())
throw new ApplicationException("Invalid mailbox");
//Gets up to maxCount messages from the pop box
folder.open(Folder.READ_WRITE);
Message[] messages = Monitor.EMPTY_MESSAGE_ARRAY;
int toMessageIndex=folder.getMessageCount();
if (toMessageIndex > 0) {
if (toMessageIndex > maxCount)
toMessageIndex = maxCount;
messages = folder.getMessages(1,toMessageIndex);
}
// Go through all the new messages and make sure they are loaded. Use the outputStream
//to force all information to be downloaded.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (int i = 0; i < messages.length && shouldRun(); i++) {
try {
//Force the download of all message information
bos.reset();
messages[i].writeTo(bos);
getLog().enter(
this,
"[readAndClearInBox] Read message to " + messages[i].getAllRecipients()[0].toString());
} catch (Exception mex) {
getLog().error(this, mex, "[readAndClearInBox] Message exception");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
try {
Monitor.dumpEnvelope(getLog(), pw, messages[i]);
} catch (Exception ex) {
getLog().error(this, mex, "[readAndClearInBox] Could only display faulty message.");
} finally {
pw.flush();
getLog().enter(this, "[readAndClearInBox]" + sw.toString());
}
} finally {
//Mark the message for deletion
messages[i].setFlag(Flags.Flag.DELETED, true);
}
}
//Close folder and expunge all deleted messages, unless the read was aborted
if (shouldRun()) {
getLog().enter(this,"Found " + messages.length + " messages; closing inbox.");
folder.close(true);
store.close();
return messages;
} else {
getLog().enter(this,"Found " + messages.length + " messages; closing inbox without expunging.");
folder.close(false);
store.close();
_bShouldRun = true;
return Monitor.EMPTY_MESSAGE_ARRAY;
}
}

Open javamail folder failed

I developed an email website using javamail and apache-james and it works well mostly. But some user got Open failed Exception and cannot receive new mail.
The code of receive email:
Session mailSession = Session.getInstance(System.getProperties(), null);
mailSession.setDebug(false);
Store store = null;
Folder folder = null; //javax.mail.Folder
try {
store = mailSession.getStore(SParam.PROTOCOL);
store.connect(Property.getPop3(), userName, password);
logger.info("trying to receive emails from james server...");
folder = store.getFolder("INBOX");
try {
if (!folder.isOpen()) {
folder.open(Folder.READ_WRITE); //the point of throwing the exception
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//receive email from james server.
} catch (Exception e) {
logger.error("Email Receive Error!" + StackTraceStr.st2str(e));
try {
folder.close(true);
} catch (Exception e2) {
}
} finally {
try {
store.close();
} catch (Exception cloex) {
}
}
In most cases, it works just fine. But still got the error occasionally:
javax.mail.MessagingException: Open failed;
nested exception is:
java.io.IOException: STAT command failed: null
at com.sun.mail.pop3.POP3Folder.open(POP3Folder.java:228)
at com.csc.mail.jsh.mail.core.ReceiveMail.receive(ReceiveMail.java:82)
at com.csc.mail.jsh.mail.core.ReceiveMail.run(ReceiveMail.java:222)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.io.IOException: STAT command failed: null
at com.sun.mail.pop3.Protocol.stat(Protocol.java:366)
at com.sun.mail.pop3.POP3Folder.open(POP3Folder.java:203)
... 3 more
Waiting your help and thanks a lot!
I debug and debug, finally found the STAT command failed! when STAT command got an error, there's an exception of james, but that makes no sence!
21/11/12 14:39:16 ERROR pop3server: Exception during connection from 127.0.0.1
(127.0.0.1) : An exception occurred getting a database connection.
org.apache.avalon.framework.CascadingRuntimeException: An exception occurred getting a database connection.
at org.apache.james.userrepository.AbstractJdbcUsersRepository.openConnection(AbstractJdbcUsersRepository.java:617)
at org.apache.james.userrepository.AbstractJdbcUsersRepository.getUserByName(AbstractJdbcUsersRepository.java:521)
at org.apache.james.userrepository.AbstractUsersRepository.test(AbstractUsersRepository.java:270)
at org.apache.james.core.LocalUsersRepository.test(LocalUsersRepository.java:90)
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 org.apache.avalon.phoenix.components.application.BlockInvocationHandler.invoke(BlockInvocationHandler.java:134)
at $Proxy4.test(Unknown Source)
at org.apache.james.pop3server.POP3Handler.doPASS(POP3Handler.java:537)
at org.apache.james.pop3server.POP3Handler.parseCommand(POP3Handler.java:479)
at org.apache.james.pop3server.POP3Handler.handleConnection(POP3Handler.java:277)
at org.apache.james.util.connection.ServerConnection$ClientConnectionRunner.run(ServerConnection.java:432)
at org.apache.excalibur.thread.impl.ExecutableRunnable.execute(ExecutableRunnable.java:55)
at org.apache.excalibur.thread.impl.WorkerThread.run(WorkerThread.java:116)
Caused by: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
The Connection descriptor used by the client was: 192.168.250.23:1521:csmis
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:261)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:439)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:37)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:290)
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:771)
at org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:95)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:540)
at org.apache.james.util.dbcp.JdbcDataSource.getConnection(JdbcDataSource.java:220)
at org.apache.james.userrepository.AbstractJdbcUsersRepository.openConnection(AbstractJdbcUsersRepository.java:614)
... 15 more
All application runs on the same server, and there's only a few users online(when I test it, only me use it). The error just appear occasionally. Why?
It seems to be a mail server issue. STAT command is used to show number of messages. Normally STAT is the first command to run after successfully connected to the mail server.
Try to use mailSession.setDebug(true) to enter debug mode to get more error logs.
I had contact with Apache James and finally found the answer. You can find it at here: STAT command failed occasionally. At the end of the page, the thread had been listed.

vysper server login fail

I'm making a vysper xmpp server.
Here's my code:
public static void main(String[] args) throws Exception {
XMPPServer server = new XMPPServer("myserver.org");
StorageProviderRegistry providerRegistry = new MemoryStorageProviderRegistry();
AccountManagement accountManagement = (AccountManagement) providerRegistry.retrieve(AccountManagement.class);
Entity user = EntityImpl.parseUnchecked("user#myserver.org");
accountManagement.addUser(user, "password");
server.setStorageProviderRegistry(providerRegistry);
server.addEndpoint(new TCPEndpoint())
server.setTLSCertificateInfo(new File("keystore.jks"), "boguspw");
//server.setTLSCertificateInfo(new File("bogus_mina_tls.cert"), "boguspw");
server.start();
System.out.println("Vysper server is running...");
server.addModule(new EntityTimeModule());
server.addModule(new VcardTempModule());
server.addModule(new XmppPingModule());
server.addModule(new PrivateDataModule());
}
I've tried both certificate files. (keystore.jks,bogus_mina_tls.cert)
After I start the server, it connects to it, and tries to login but it can't login.
SmackConfiguration.setPacketReplyTimeout(5000);
config = new ConnectionConfiguration("myserver.org", port, "localhost");
config.setSelfSignedCertificateEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
config.setSASLAuthenticationEnabled(true);
// config.setKeystorePath("keystore.jks");
// config.setTruststorePath("keystore.jks");
config.setKeystorePath("bogus_mina_tls.cert");
config.setTruststorePath("bogus_mina_tls.cert");
config.setTruststorePassword("boguspw");
XMPPConnection.DEBUG_ENABLED = true;
connection = new XMPPConnection(config);
try {
connection.connect();
} catch (XMPPException e) {
System.out.println("Error connect");
e.printStackTrace();
}
System.out.println("Connected: " + connection.isConnected());
try {
System.out.println(connection.isAuthenticated());
connection.login("user", "password");
} catch (XMPPException e) {
System.out.println("Error login");
e.printStackTrace();
}
I catch this exception:
SASL authentication PLAIN failed: incorrect-encoding: at
org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:337)
at
org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
at org.jivesoftware.smack.Connection.login(Connection.java:348) at
com.protocol7.vysper.intro.WorkingClient.init(WorkingClient.java:57)
at
com.protocol7.vysper.intro.WorkingClient.(WorkingClient.java:27)
at com.protocol7.vysper.intro.Runclient.main(Runclient.java:11)
I've seen these examples (1st, 2nd) but they don't work.
At first please note that the server certificate is not used for user authentication, it is used to provide secure communication channel between client and server.
From the log you can see that your authentication method is "SASL PLAIN", using a user and password.
On the server, you are setting username/password as:
accountManagement.addUser("user#myserver.org", "password");
but on the client you're using
connection.login("user", "password");
This doesn't fit with the error message you are posting, but I'd suggest you try again with correct user/password.

Categories