Simple example to access Gmail by Java

To show the folders and their message counts:
        Properties props = System.getProperties();
props.setProperty("mail.pop3.port", prop.getProperty("995"));
Session session = Session.getInstance(props, null);

Store store = session.getStore("imaps");

store.connect("pop.gmail.com", "name", "password");

javax.mail.Folder[] dfolders = store.getDefaultFolder().list("*");
for (Folder f : dfolders) {
System.out.println(f.getFullName());

if ((f.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
System.out.println(f.getMessageCount());
}

}
The output:
INBOX
25
[Gmail]
[Gmail]/All Mail
69
[Gmail]/Drafts
0
[Gmail]/Important
1
[Gmail]/Sent Mail
6
[Gmail]/Spam
4761
[Gmail]/Starred
0
[Gmail]/Trash
121

Open folder and delete the messages
IMAPFolder folder = null;
String[] folders = new String[]{"INBOX", "[Gmail]/Spam"};

for (String fname : folders) {

folder = (IMAPFolder) store.getFolder(fname);
folder.open(Folder.READ_WRITE);
int c = folder.getMessageCount();
System.out.println(c);

Map map = new HashMap<>();
for (int i = c; i > 0; i--) {

Enumeration
headers = message.getAllHeaders();

while (headers.hasMoreElements()) {
Header h = headers.nextElement();
//h.getName()
//h.getValue()

}

if (message.isSet(Flags.Flag.SEEN)) {
message.setFlag(Flags.Flag.DELETED, true); //mark this message as deleted
}

}
}
folder.expunge(); //
folder.close(true);
on Github

Comments