views:

120

answers:

2

I am trying to perform a search of my gmail using Java. With JavaMail I can do a message by message search like so:

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "myUsername", "myPassword");

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);

SearchTerm term = new SearchTerm() {
  @Override
  public boolean match(Message mess) {
    try {
      return mess.getContent().toString().toLowerCase().indexOf("boston") != -1;
    } catch (IOException ex) {
      Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MessagingException ex) {
      Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
  }
};

Message[] searchResults = inbox.search(term);
for(Message m:searchResults)
  System.out.println("MATCHED: " + m.getFrom()[0]);

But this requires downloading each message. Of course I can cache all the results, but this becomes a storage concern with large gmail boxes and also would be very slow (I can only imagine how long it would take to search through gigabytes of text...).

So my question is, is there a way of searching through mail on the server, a la gmail's search field? Maybe through Microsoft Exchange?

Hours of Googling has turned up nothing.

A: 

Connect to the Exchange IMAP store and use javax.mail.search.SearchTerm

james
+1  A: 

You can let the server do the search for you, with the appropriate IMAP command. The SEARCH command will only get you so far, what you probably need is the SORT command. SORT isn't implemented in JavaMail but the documentation shows how you can implement it yourself:

http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/IMAPFolder.html#doCommand(com.sun.mail.imap.IMAPFolder.ProtocolCommand)

(I couldn't figure out how to link to a URL with parentheses)

Martin
Thanks. I'm can connect to the server and IMAPFolder, but when I issue a doCommand (as per the example in the link), response.isOK() is false. I got an exception the first time (which I can't seem to recreate), but now it just returns:A5 BAD Unknown command: SORTMy connection code:IMAPStore store = new IMAPStore(session, new URLName("imap://myusername:[email protected]/"));store.connect();IMAPFolder folder = (IMAPFolder) store.getFolder("inbox");Then I do the same folder.doCommand() call as the example. Any ideas about why this isn't working?sorry for the formatting.
twofivesevenzero
`BAD Unknown command: SORT` would mean the server doesn't support the `SORT` command. The IMAP server tells you what features are supported when you issue the `CAPABILITY` command (should be the first thing JavaMail sends) so you could examine that response to see what features are available.
Martin