细心!用心!耐心!

吾非文人,乃市井一俗人也,读百卷书,跨江河千里,故申城一游; 一两滴辛酸,三四年学业,五六点粗墨,七八笔买卖,九十道人情。

BlogJava 联系 聚合 管理
  1 Posts :: 196 Stories :: 10 Comments :: 0 Trackbacks

用javaMail实现对邮件的查找

 

用javaMail来实现邮件的查找非常的容易,我把自己平时的经验总结成如下这篇文章,希望对大家能有帮助,同时也希望各位能给
如下程序多提一些自己的看法:

下面是本程序的主要框架:
//|++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


package webmail.mail.search;


import javax.mail.*;
import java.util.Iterator;
import java.util.Date;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.internet.*;
import javax.mail.search.*;

import webmail.mail.search.PersonalTerm;
import webmail.mail.search.JAttachTerm;
import webmail.mail.search.JBodyTerm;

import webmail.mail.*;
import webmail.mail.MimeMessageParser;

/**
 * description: 一个简单的邮件查找类,用来查找特定主题的邮件,特定日期,或者
 * 是包含有附件的邮件
 * lastmodify: 2004-10-09
 * <p>注: JavaMail API中的javax.mail.search包中的BodyTerm和AttachTerm在使用时
 * 有问题,这里使用我扩展SearchTerm的JBodyTerm和JAttachTerm,同时由于javax.
 * mail.search包中的SubjectTerm取邮件主题直接调用JavaMail的getSubject()方法
 * 这样得到的结果有时候不正常,可以扩展SearchTerm来定义自己的Term(这个是下
 * 一篇文章要写的内容)
 * @author wang weiping of BeiJing flow.Inc
 * @version v1.0.1
 */
public class MessageQuerier {

      private String body = "";
      private ArrayList list = new ArrayList();
      private int comparison = ComparisonTerm.EQ;

      public static final String OR = "or";
      public static final String AND = "and";
     
      //默认构造方法
      public MessageQuerier() {}

      public void setComparison(String string) {
            if (string.equals(">")) {
                  comparison = ComparisonTerm.GE;
            } else if (string.equals("<")) {
                  comparison = ComparisonTerm.LE;
            }
      }

      public int getComparison() {
            return this.comparison;
      }

      /**
       * 根据指定的字符串来查找所有邮件主题中包含此字符串的所有邮件
       * @param subject 邮件主题中所要包含的字符串
       */
      public void setSubject(String subject) {
            SearchTerm subterm = new JSubjectTerm(subject);
            list.add(subterm);
      }
     
      public void setRecipients(String recipients){
            try{
                  SearchTerm rterm = new RecipientTerm   (Message.RecipientType.TO,new InternetAddress(recipients));
                  list.add(rterm);
            }catch(Exception ex){
                  //ignore exception
                  ex.printStackTrace();
            }
      }
     
      public void setRecipientPersons(String recipientPersons){
            SearchTerm rpTerm = new RecipientPersonTerm(recipientPersons);
            list.add(rpTerm);
      }
     
      /**
       * 根据指定的字符串来查找发件人地址中包含此字符串的所有邮件
       * @param from 设置发件人地址中要包含的字符串
       */
      public void setFrom(String from) {
            try {
                  SearchTerm fterm = new FromTerm(new InternetAddress(from));
                  list.add(fterm);
            } catch (Exception ex) {
                  System.err.println("CoffeeWebMail reportException: " + ex.toString());
                  ex.printStackTrace();
            }
      }

      /**
       * Created 2004-10-9
       * 此类用了自定义的查找器PersonalTerm,此类从javax.mail.search.StringTerm
       * 中继承下来,重写了StringTerm类的match()方法
       * <p>根据发件人的姓名来查找此发件人发来的所有邮件</p>
       * @param personal 设置发件人的姓名
       */
      public void setPersonal(String personal) {
            try {
                  PersonalTerm pterm = new PersonalTerm(personal);
                  list.add(pterm);
            } catch (Exception ex) {
                  System.err.println("CoffeeWebMail reportException: " + ex.toString());
                  ex.printStackTrace();
            }
      }

      /**
       * Created 2004-10-09
       *
       * 此类用到了自定义的查找器JAttachTerm,此类从javax.mail.search.SearchTerm中
       * 直接继承下来,重写了SearchTerm类的match()方法
       * <p>根据是否包含附件来查找匹配的所有邮件</p>
       * @param flag 是否有附件的标志 true or false
       */
      public void setAttachFlag(boolean flag) {
            try {
                  SearchTerm jaterm = new JAttachTerm(flag);
                  list.add(jaterm);
            } catch (Exception ex) {
                  System.err.println("CoffeeWebMail reportException: " + ex.toString());
                  ex.printStackTrace();
            }
      }


      /**
       * Created 2004-10-09
       *
       * 根据给定的字符串来查找邮件正文中包含此字符串的所有邮件
       * @param pattern 邮件正文要包含的字符串
       */
      public void setBodyText(String pattern) {
            SearchTerm jbterm = new JBodyTerm(pattern);
            list.add(jbterm);
      }


      // note: The dateFormat is <yyyy-MM-dd> eg: [2004-7-10]
      public void setReceiveDate(String date) {
            int comparison = getComparison();
            Date recdate = null;
            try {
                  recdate = getSearchDate(date);
                  SearchTerm recterm = new ReceivedDateTerm(comparison, recdate);
                  list.add(recterm);
            } catch (Exception ex) {
                  System.err.println("CoffeeWebMail reportException: " + ex.toString());
                  ex.printStackTrace();
            }
      }

      public void setSentDate(String date) {
            int comparison = getComparison();
            Date sentdate = null;
            try {
                  sentdate = getSearchDate(date);
                  SearchTerm recterm = new SentDateTerm(comparison, sentdate);
                  list.add(recterm);
            } catch (Exception ex) {
                  System.err.println("CoffeeWebMail reportException: " + ex.toString());
                  ex.printStackTrace();
            }
      }

      /**
       * 返回所有符合搜索条件的邮件数组
       * return all messages that according the searchterm.
       * param--srchmode["and" or "or"]
       * @param folder Folder  要搜索的邮件夹
       * @param srchmode String 搜索模式,搜索模式为其中之一: MessageQuerier.OR or MessageQuerier.AND
       * @return Message[]  符合条件的所有消息数组
       */
      public Message[] getSrchMessages(Folder folder, String srchmode) {
            SearchTerm sterm = null;
            Message[] msgs = null;
        //if(list.size() == 0) return null;
            SearchTerm[] sterms = new SearchTerm[list.size()];
            try {
                  for (int i = 0; i < sterms.length; i++) {
                        sterms[i] = (SearchTerm) list.get(i);
                  }
                  if (sterms.length > 1) {
                        if (srchmode.equals("and")) {
                              //debug info
                              //System.out.println("and term :"+sterms.length);
                              sterm = new AndTerm(sterms);
                        } else if (srchmode.equals("or")) {
                              sterm = new OrTerm(sterms);
                        }
                  } else if (sterms.length == 1) {
                        //debug info
                        //System.out.println("sterm's length is 1");
                        sterm = sterms[0];
                  }
                  if (sterm == null) msgs = folder.getMessages();
                  else
                msgs = folder.search(sterm);

            } catch (Exception ex) {
                  System.err.println("CoffeeWebMail reportException: " + ex.toString());
                  ex.printStackTrace();
            }
            return msgs;
      }

      //辅助方法
      private Date getSearchDate(String date) {
            String[] ymd = date.split("-");
            int year, month, day;
            Date srchdate = null;
            try {
                  year = Integer.parseInt(ymd[0]);
                  month = Integer.parseInt(ymd[1]) - 1;
                  day = Integer.parseInt(ymd[2]);
                  Calendar cal = Calendar.getInstance();
                  cal.set(year, month, day);
                  srchdate = cal.getTime();
            } catch (Exception ex) {
                  System.err.println("CoffeeWebMail reportException: " + ex.toString());
                  ex.printStackTrace();
            }
            return srchdate;
      }

      //一个测试代码
      public static void main(String args[])
          throws Exception {
            String host = "pop.mail.yahoo.com.cn"; //pop.mail.yahoo.com.cn
            String username = "wwp_1124"; //wwp_1124
            String password = "3061643"; // passwd
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("pop3");
            store.connect(host, username, password);
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            MessageQuerier mq = new MessageQuerier();
            //mq.setAttach(true);
            //mq.setAttachFlag(true);
            mq.setFrom("lcd@gxsw.com");
            //mq.setSubject("你好");
            //mq.setBodyText("测试");
            mq.setPersonal("林昌东");
            Message[] msgs = mq.getSrchMessages(folder, MessageQuerier.OR);
            System.out.println(msgs.length);
            for (int i = 0; i < msgs.length; i++) {
                  System.out.println("=====================================>");
                  MimeMessageParser mmp = MimeMessageParser.getMessageParser( (MimeMessage) msgs[i]);
                  System.out.println("sentDate: " + mmp.getSentDate());
                  System.out.println("Subject: " + mmp.getSubject());
                  System.out.println("from: " + mmp.getAddress(AddressType.FROM));
                  System.out.println("personal: " + mmp.getPersonal(AddressType.FROM));
                  //System.out.println("attachFlag: " + mmp.isContainAttach(msgs[i]));
            }
      }
}


总结:
     通过看上面这段代码,相信大家已经对怎样使用JavaMail API 来进行邮件查找已经
有了一个大概的了解了吧!在上面的代码中主要是使用了自己定义的SearchTerm来进行对
邮件的查找,你可以扩展javax.mail.search包中的SearchTerm来编写属于你自己的Term
欢迎大家提出宝贵意见,我的msn是: coffeecat_1124@hotmail.com

还有就是我的代码中引用了MimeMessageParser这个类,这个类的主要作用是用来做邮件
解析的。在下一篇文章中,我会把MimeMessageParser这个类和其他用到的一些自定义
的类上传上去,希望大家可以顺利的测试程序代码,上面的文章只是给出一个思路让大
家来参考,希望是来学习思路,而不是直接套用别人的代码。

posted on 2007-05-06 12:05 张金鹏 阅读(354) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: