Link to home
Start Free TrialLog in
Avatar of umanarayan
umanarayan

asked on

SEARCH command using java mail API

hi,

The following IMAP Command list the message numbers of unseen mails :(syntax)

<machinename> search unseen
3 8 9

I want to do the same using java mail api.
I don't know how to use the search method in IMAPProtocol to get the above result.

help me.
Regards,
uma
Avatar of Venci75
Venci75

try this:
 Properties props = new Properties();
 Session session = Session.getDefaultInstance(props,null);
 store = session.getStore("imap");

 store.connect("mail","user","pwd");
 folder = store.getFolder("INBOX");
 folder.open(Folder.READ_ONLY);
 Message message[] = folder.getMessages();
 for(int i =0, n =message.length; i<n; i++){
    if (!message[i].getFlags().contains(Flags.Flag.SEEN)) {
        System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject());
    }
  }
 folder.close(false);
 store.close();
Avatar of umanarayan

ASKER

hi,

I accept that above code will work perfectly. But it will loop thru' all messages in the folder. Instead i like to fetch only the messages which has a particular flag(SEEN or RECENT etc).

In sense like to execute the imap search commands (RFC 2060) using the java mail API and fetch the results.

In java mail API, IMAPProtocol class contains the method search but it does not provides this functionality of fetching only message numbers.

Regards,
uma
ok - then try this:

 Properties props = new Properties();
 Session session = Session.getDefaultInstance(props,null);
 store = session.getStore("imap");

 store.connect("host","user","password");
 folder = store.getFolder("INBOX");
 folder.open(Folder.READ_ONLY);
 Flags flags = new Flags(Flags.Flag.SEEN);
 javax.mail.search.FlagTerm term = new javax.mail.search.FlagTerm(flags, false);
 Message message[] = folder.search(term);
 for(int i =0, n =message.length; i<n; i++){
    System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject());
  }
 folder.close(false);
 store.close();
hi,

I need to fetch only UNSEEN mails.

thanks & regards,
uma
ASKER CERTIFIED SOLUTION
Avatar of Venci75
Venci75

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial