I wish you

今天, 你java了吗

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  17 Posts :: 19 Stories :: 8 Comments :: 0 Trackbacks
从网上参考了一点, 然后自己写一点, 呵呵, 虽然简单, 但是很实用

package helloworld;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.SearchTerm;
import javax.mail.search.SentDateTerm;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ReadSupportMailAgent extends Authenticator implements Runnable {//此段代码用来进行服务器对用户的认证 
   
   
    Log log = LogFactory.getLog(getClass().getName());
   
    String username=null;
    String host =null;
    String password=null;
   
    Properties props=null;
    Session session = null;
   
    boolean inited = false;
    Date latestSentDate = null;
   
    private static TypeConvert tc = new TypeConvert();
   
    public ReadSupportMailAgent(String host, String username, String password) {
        super();
        this.host = host;
        this.username = username;
        this.password = password;
    }

    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }

    public static void main(String[] args) throws Exception {
        ReadSupportMailAgent gm = new ReadSupportMailAgent("pop3.126.com", "username","password");
        Thread t = new Thread(gm);
        t.start();
    }
   
    boolean exit = false;
    int interval = 1*60000;
    public void run() {
        while (!exit) {
            try {
                receive();
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                log.debug("GetMail agent is interrupted.", e);
                exit = true;
                log.info("quit the agent.");
            }
        }
    }
   
    void receive()  {
        Folder folder = null;
        Store store = null;
        try {
            init();
            store = session.getStore("pop3");
            store.connect(host, username, password);

            //open inbox in read_only mode 
            folder = store.getFolder("INBOX"); 
            folder.open(Folder.READ_ONLY); //只读模式, 把邮件留在服务器上面

           
            Message messages[];
            if(latestSentDate==null){ //本地没有记录最新的邮件的发送时间, 那么读取所有的邮件
                log.info("receiving all mails ... ");
                messages = folder.getMessages();

            }else{ //搜索大于latestSentDate的邮件
                SearchTerm st = new SentDateTerm(SentDateTerm.GT, latestSentDate);
                log.info("start searching mails after " + showSentDate() );
                messages = folder.search(st);
            }
            log.info(messages.length+" mails received.");
           
            if(messages!=null && messages.length>0)
                processMessages(messages);
           
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(folder!=null)
                folder.close(true); 
               
                if(store!=null)
                store.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    private void init() {
        if(!inited) {
            props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true"); 
            session = Session.getDefaultInstance(props, this );
           
            // 从某个地方读取上次接收邮件的最迟时间
            //this.latestSentDate = "2006-05-01";
          
            // 从某个地方读取循环检查新邮件的间隔时间
            String iInterval =  5 * 60000;//默认5分钟读取一次
           
            inited = true;
        }
    }

    private void processMessages(Message[] message) throws MessagingException, SaksException {
       
        log.info("total mails: " + message.length);

        Date tempSentDate = latestSentDate;
       
        List vs = new LinkedList();
       
        for (int i = 0, n = message.length; i < n; i++) {
       
            String subject = message[i].getSubject();
           
            Date sentDate = message[i].getSentDate();
            tempSentDate = max(tempSentDate, sentDate); //记录邮件的最迟时间
               
            // 其他的处理代码 ....
        }
       
        //处理成功后, 更新这个时间
        latestSentDate = tempSentDate;
       
    }

    private Date max(Date date1, Date date2) {
        if(date1==null)
            return date2;
        else if(date2==null)
            return date1;
       
        if(date1.after(date2))
            return date1;
        else
            return date2;
    }
   
    public String showSentDate() {
        // 格式化这个时间成为你想要的任何格式
        if(this.latestSentDate==null)return "";
        else
             return this.latestSentDate.toString();
    }
}

posted on 2006-04-26 10:27 Iwishyou 阅读(617) 评论(0)  编辑  收藏 所属分类: Java

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


网站导航: