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;
}
}
Related
I'm creating an app which generates a CSV file and some PDFs. I want my app to send those files to a server via FTPS protocol.
I'm using Apache Commons Net FTP library and it was perfectly working when I had "Require TLS session resumption on data connection when using PORT P" unchecked, but since I enabled it I can't send my files.
An error appeared :
450 TLS session of data connection has not resumed or the session does not match the control connection.
After some researches on this site I have overriden _prepareDataSocket_ in order to overcome this problem but now it just creates empty files on the server.
There is my overriden function :
#Override
protected void _prepareDataSocket_(final Socket socket) throws IOException {
if (socket instanceof SSLSocket) {
// Control socket is SSL
final SSLSession session = ((SSLSocket) _socket_).getSession();
if (session.isValid()) {
final SSLSessionContext context = session.getSessionContext();
try {
final Field sessionHostPortCache = context.getClass().getDeclaredField("sessionHostPortCache");
sessionHostPortCache.setAccessible(true);
final Object cache = sessionHostPortCache.get(context);
final Method method = cache.getClass().getDeclaredMethod("put", Object.class, Object.class);
method.setAccessible(true);
method.invoke(cache, String
.format("%s:%s", socket.getInetAddress().getHostName(), String.valueOf(socket.getPort()))
.toLowerCase(Locale.ROOT), session);
method.invoke(cache, String
.format("%s:%s", socket.getInetAddress().getHostAddress(), String.valueOf(socket.getPort()))
.toLowerCase(Locale.ROOT), session);
} catch (NoSuchFieldException e) {
throw new IOException(e);
} catch (Exception e) {
throw new IOException(e);
}
} else {
throw new IOException("Invalid SSL Session");
}
}
}
and this is what FileZilla Server displays:
FileZilla Response
will this answer on another forum help?
http://forum.rebex.net/5673/450-error-connecting-to-ftp-requiring-explicit-ftp-over-tls
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.
This is my entire java code. If I comment the line:
objCon = DriverManager.getConnection(props.getString("url")); the mail is sending correctly. Else, its throwing the error - Could not connect to SMTP host: mail.companyname.com, port: 25;
public class PullRec {
private static final Logger LOG_TRACE = Logger.getLogger("debugLogger");
public static void main(String[] args) throws Exception {
Connection objCon = null;
PropertyResourceBundle props;
props = (PropertyResourceBundle) ResourceBundle.getBundle("com.cts.properties.config");
try {
Class.forName(props.getString("dbdriver"));
// If I comment the below line, the sendmail function works perfectly..!!
objCon = DriverManager.getConnection(props.getString("url"));
}
catch(Exception e) {
LOG_TRACE.info("DBConnection.java FILE ERROR: Disconnected due to "+e);
}
sendmail("Test");
}
public static void sendmail(String strBody) {
String to = "sarath#companyname.com";
String from = "sarath#companyname.com";
String host = "mail.companyname.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("java.net.preferIPv4Stack","true");
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("CTS Monitor");
message.setContent(strBody,"text/html" );
Transport.send(message);
System.out.println("Sent message successfully....");
}
catch (MessagingException e) {
e.printStackTrace();
}
}
}
Your mail method is clearly setting the SMTP server hostname to "<hostname>". That is never going to work. You need to replace that with the real DNS hostname of the SMTP server you are attempting to use.
(Your from and to addresses are unlikely to work either ...)
If you have done that and it still isn't working, then check that you have got the (real) hostname and port correct, and that the SMTP server on that host / port are alive.
I notice that you have commented out the call to mail(String) which configures the mail server, and I'm not sure what your Mail object is, or what the sendmail method is actually doing.
(Note: this is NOT all of your Java code, because if it was, it doesn't compile!)
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.
I am trying to download a file from ftp server using com.enterprisedt.net.ftp.FileTransferClient and the file name is "ABC.DEF.GHI.JKL(0)", This is a mainframe file and it is a valid file name(checked with mainframe admin).
public static void main(String[] args) {
// extract command-line arguments
String host = "111.111.111.111";
String username = "bbbbbbbb";
String password = "cccccccccp";
String filename = "ABC.DEF.GHI.JKL(0)";
// set up logger so that we get some output
Logger log = Logger.getLogger(ConnectToServer.class);
Logger.setLevel(Level.INFO);
FileTransferClient ftp = null;
try {
// create client
log.info("Creating FTP client");
ftp = new FileTransferClient();
// set remote host
log.info("Setting remote host");
ftp.setRemoteHost(host);
ftp.setUserName(username);
ftp.setPassword(password);
// connect to the server
log.info("Connecting to server " + host);
ftp.connect();
log.info("Connected and logged in to server " + host);
//Downloading file from server
log.info("Downloading file");
ftp.downloadFile(filename+".copy", filename);
log.info("File downloaded");
// Shut down client
log.info("Quitting client");
ftp.disconnect();
log.info("Example complete");
} catch (Exception e) {
e.printStackTrace();
}
}
The error i am receiving is :
ERROR [FTPClient] 2 Mar 2012 21:44:08.359 : Caught and rethrowing exception in initGet() : Invalid data set name "ABC.DEF.GHI.JKL(0)". Use MVS Dsname conventions.
com.enterprisedt.net.ftp.FTPException: 501 Invalid data set name "ABC.DEF.GHI.JKL(0)". Use MVS Dsname conventions.
at com.enterprisedt.net.ftp.FTPControlSocket.validateReply(FTPControlSocket.java:1223)
at com.enterprisedt.net.ftp.FTPClient.initGet(FTPClient.java:3109)
at com.enterprisedt.net.ftp.FTPClient.getData(FTPClient.java:3156)
at com.enterprisedt.net.ftp.FTPClient.getFile(FTPClient.java:2970)
at com.enterprisedt.net.ftp.FTPClient.get(FTPClient.java:2356)
at com.enterprisedt.net.ftp.FileTransferClient.downloadFile(FileTransferClient.java:703)
at com.enterprisedt.net.ftp.FileTransferClient.downloadFile(FileTransferClient.java:683)
at com.bluecrossma.ConnectToServer.main(ConnectToServer.java:47)
Please suggest me on how to resolve this problem.
Thanks in Advance
Found the answer in this link: torsas.ca/attachments/File/03012008/FTP_Fileref.pdf Just needed to add single quotes inside the double quotes..Thanks guys.