1、主要代碼:

/** *//**
* 搜索郵件
*/

public static void search(String subject, String from, boolean or) throws Exception
{
Session session = Session.getDefaultInstance(System.getProperties(), null);
// session.setDebug(true);
Store store = session.getStore(new URLName("imap://test:test@127.0.0.1"));
store.connect();
Folder folder = store.getDefaultFolder();
// 在收件箱中搜索
folder = folder.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
List<SearchTerm> terms = new ArrayList<SearchTerm>();
// 按主題查詢
terms.add(new SubjectTerm(subject));
// 按發(fā)件人查詢
terms.add(new FromStringTerm(from));
// 一個小時內(nèi)的郵件(我本地的Megic Winmail郵件服務(wù)器查不到內(nèi)容)
// long time = System.currentTimeMillis();
// SentDateTerm dateTerm = new SentDateTerm(ComparisonTerm.GE, new Date(
// time - 60 * 60 * 1000));
// terms.add(dateTerm);
SearchTerm arrays[] = new SearchTerm[terms.size()];
terms.toArray(arrays);
SearchTerm term = or ? new OrTerm(arrays) : new AndTerm(arrays);
Message[] msgs = folder.search(term);
System.out.println("FOUND " + msgs.length + " MESSAGES");

for (int i = 0; i < msgs.length; i++)
{
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpEnvelope(msgs[i]);
}
}


/** *//**
* 打印郵件的內(nèi)容
*
* @param m
* @throws Exception
*/

public static void dumpEnvelope(Message m) throws Exception
{
Address[] a;

if ((a = m.getFrom()) != null)
{
for (int j = 0; j < a.length; j++)
System.out.println("FROM: " + a[j].toString());
}

if ((a = m.getRecipients(Message.RecipientType.TO)) != null)
{

for (int j = 0; j < a.length; j++)
{
System.out.println("TO: " + a[j].toString());
}
}
System.out.println("SUBJECT: " + m.getSubject());
Date d = m.getSentDate();
System.out.println("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));
}


public static void main(String[] args)
{

try
{
search("subject", "test2@test.com", false);
System.out.println("\n");
search("Fw: test", "test2@test.com", false);
System.out.println("\n");
search("null", "test2@test.com", true);

} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2、測試輸出:
FOUND 0 MESSAGES


FOUND 1 MESSAGES
--------------------------
MESSAGE #1:
FROM: test2 <test2@test.com>
TO: test <test@test.com>
SUBJECT: Fw: test
SendDate: Tue Apr 21 20:38:23 CST 2009


FOUND 2 MESSAGES
--------------------------
MESSAGE #1:
FROM: test2 <test2@test.com>
TO: test <test@test.com>
SUBJECT: 測試郵件
SendDate: Mon Apr 20 21:42:53 CST 2009
--------------------------
MESSAGE #2:
FROM: test2 <test2@test.com>
TO: test <test@test.com>
SUBJECT: Fw: test
SendDate: Tue Apr 21 20:38:23 CST 2009

3、相關(guān)說明:
如果采用debug模式的話,可以看到調(diào)用和搜索串之間的對應(yīng)關(guān)系:
第一次:SEARCH SUBJECT subject FROM test2@test.com ALL
第二次:SEARCH SUBJECT "Fw: test" FROM test2@test.com ALL
第三次:SEARCH OR SUBJECT null FROM test2@test.com ALL