Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I perform a search on mail server in Java?

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.

like image 628
smurthas Avatar asked Mar 09 '10 01:03

smurthas


People also ask

How does Java Mail API work?

A: The JavaMail API is a set of abstract APIs that model a mail system. The API provides a platform independent and protocol independent framework to build Java technology based email client applications. The JavaMail API provides facilities for reading and sending email.

What is SMTP in Java?

SMTP is an acronym for Simple Mail Transfer Protocol. It is an Internet standard for electronic mail (e-mail) transmission across Internet Protocol (IP) networks. SMTP uses TCP port 25.

What is IMAP in Java?

IMAP is Acronym for Internet Message Access Protocol. It is an Application Layer Internet protocol that allows an e-mail client to access e-mail on a remote mail server. An IMAP server typically listens on well-known port 143. IMAP over SSL (IMAPS) is assigned to port number 993.


1 Answers

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)

like image 50
Martin Avatar answered Sep 29 '22 19:09

Martin