I am trying to fetch unread mail from the INBOX from a gmail account. I wrote a small demo program and found that Gmail's pop3 behaves unexpectedly in a number of situations
POP3
public static Result getPop3FolderList()
{
Properties props = System.getProperties();
props.put("mail.store.protocol", "pop3s");
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", Application.email);
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.getInstance(props,new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Application.email, Application.pwd);
}
});
try{
Store store=session.getStore("pop3");
store.connect(Application.email,Application.pwd);
javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
String opHtml = "<ul>";
for (javax.mail.Folder folder : folders) {
if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
opHtml += "<li>" + folder.getFullName()+ "+" + folder.getMessageCount() + "</li>";
}
}
opHtml += "</ul>";
return ok(opHtml).as("text/html");
} catch(MessagingException e) {
return ok("Error in getting list.<br />" + e.getMessage()).as("text/html");
}
}
IMAP
public static Result getImapFolderList()
{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props,new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Application.email, Application.pwd);
}
});
javax.mail.Store store = session.getStore("imaps");
store.connect("imap.gmail.com", Application.email, Application.pwd);
javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
String opHtml = "<ul>";
for (javax.mail.Folder folder : folders) {
if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
opHtml += "<li>" + folder.getFullName()+ ":" + folder.getMessageCount() + "</li>";
}
}
opHtml += "</ul>";
return ok(opHtml).as("text/html");
} catch (MessagingException e) {
return ok("Error in getting list.<br />").as("text/html");
}
}
Additional Info : I have enabled pop3 only for the new mail and not from the beginning
Am I using the pop3 wrong or is it broken in gmail?
Apparently, POP3 doesn't handle folders. I had the same problem when accessing Exchange mailboxes - IMAP gets folders, POP3 only gets the Inbox.
I found more info here: How to retrieve gmail sub-folders/labels using POP3?