can't connect with pop3 server - java

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.

Related

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

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!

Authentication Error with Java Mail delegate access

I am trying to use delegate mail access through javamail. I have configured the delegate access correctly on my system. But when I try to run the following code
import java.util.Properties;
import javax.mail.*;
public class Test {
public static void main(String[] args) {
Properties props = System.getProperties();
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.smtp.ssl.enable", "true");
try {
Session session = Session.getInstance(props, null);
session.setDebug(true);
Store store = session.getStore("imaps");
store.connect(mailServerIP, 993, "myAlias/DelegateAlias", "mypassword");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for (Message message : messages) {
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
}
it shows me the following error
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:715)
at javax.mail.Service.connect(Service.java:364)
at com.adecco.smpt.TestSSL.main(TestSSL.java:26)
If I try to access my mail box instead of shared mailbox everything works well. Is there a different syntax to access the SHARED MAILBOX in JAVA?
I am using the private mail server.

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;
}
}

How to download emails into local system using java?

I need to download gmail-> emails into my local system. Idea is to convert each 'email's' content into an XML and upload it onto some other system. I am wondering if there is an API which allows me to download 'my' e-mails from gmail account onto a local hard drive (e.g c:\gmail-mails)
Here is a code snipped I got from this site.
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
//TODO store the message cntent in anXML file
}
} catch (NoSuchProviderException e) {
e.printStackTrace();//...
} catch (MessagingException e) {
e.printStackTrace();//...
}
And maybe better, also have a look at the extention of JavaMail Google made.

Unable to read the Gmail INBOX from the java code using POP API .. giving an error java.net.ConnectException: Connection timed out: connect error

props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", "xxx#gmail.com");
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getDefaultInstance(props,
new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx",
"xxx");
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", "xxxxx", "xxx");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.HOLDS_MESSAGES);
int count = fldr.getMessageCount();
System.out.println(count);
} catch (Exception exc) {
System.out.println(exc + " error");
}
// TODO Auto-generated method stub
}
Error:
javax.mail.MessagingException: Connect failed; nested exception is: java.net.ConnectException: Connection timed out: connect error
As I have added Proxy setting in this application
And set firewalls off. Still its is giving the above error.
The JavaMail FAQ has simpler code for connecting to Gmail, as well as tips for debugging connection problems and instructions for using proxy servers.

Categories