Paths

Fetching Recent Gmail Messages in your Java Programs using JavaMail.

Posted in Randomize by Rakesh on January 29, 2009

Last semester, I was working on a course project where I had to constantly fetch messages in a Gmail folder (technically a label in Gmail but it is called a Folder in IMAP lingo, so…). JavaMail API has a powerful way of doing such operations and many more and the best part is that it works just right out of the box by including .jar files (available here) in your code/project and library documentation and code samples that work are easily available.

Anyway, there is a teenie-weenie trick which you should with FlagTerm object (illustrated below) use when you want just the recent messages, i.e. messages after last login in your mailbox. Mind you that my program used to log in using my Gmail account credentials, fetch these messages and then sign out so technically every time I was logging in a fresh. Here’s the code (sorry about no code-indentation, wordpress editor makes it seem like lot of work):

public static String[] FetchRecentIMAPMessages()
{
try
{

FlagTerm onlyRecent= new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] msgsRequired = folder.search(onlyRecent);

String [] messagesToReturn = new String[msgsRequired.length];

FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add(“X-Mailer”);
folder.fetch(msgsRequired, fp);

for (int i = 0; i< msgsRequired.length; i++)
{

messagesToReturn[i] = ComposeMessage(msgsRequired[i]);
System.out.print(messagesToReturn[i]);
msgsRequired[i].setFlag(Flags.Flag.SEEN, true);

}
folder.close(false);
store.close();
return messagesToReturn;

}
catch (Exception iex)
{
System.out.println(“Exception getting all Unread messages:\n “+iex.getMessage());
return null;
}

One Response

Subscribe to comments with RSS.

  1. [...] This cup of tea was served by: Paths [...]


Leave a Reply