If you want all mails in folder inbox do this:
public static void checkMail(String username, String password) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", username, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
for (Message msg : msgs) {
try {
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
// close folder and store (normally in a finally block)
inbox.close(false);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
If you want mails from other folders to you have to do the same for all folders. You get them with store.getDefaultFolder().list() (do this recursive for all folders because folders can have subfolders)
protected void recurseFolders(final Folder folder) {
// folder can hold messages
if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
// process them
}
// folder can hold other folders
if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
for (final Folder subfolder : folder.list()) {
// process them recursive
recurseFolders(subfolder);
}
}
}
Look here: https://github.com/salyh/elasticsearch-river-imap