欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用JavaMail对收件箱的邮件正文表格进行解析

程序员文章站 2022-03-27 07:51:37
...

所用jar包:jsoup-1.7.3.jar,com.springsource.javax.mail-1.4.5.jar

链接: https://pan.baidu.com/s/1VifOJdH04NXfM4b3mrDqww 提取码: pkt6

1.连接邮件服务器,获取规定时间内收件箱的邮件

public class InterceptMail {
    private static Logger logger = Logger.getLogger(GreylistInterceptMailAna.class);
    public static String AUTH;
    public static String PASSWORD;
    public static String USERS;
    public static String USERNAME;
    private static String FROMUSER;
    private static String TITLE;
    private Date msgSendTime;


    static{
        Properties p = new Properties();
        try {
            p.load(new InputStreamReader(Object.class.getResourceAsStream("/mail.properties"), "utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        AUTH=p.getProperty("mail.receive.auth");
        PASSWORD=p.getProperty("mail.receive.password");
        USERS=p.getProperty("mail.receive.users");
        USERNAME=p.getProperty("mail.receive.username");
        FROMUSER=p.getProperty("mail.send.users");
        TITLE=p.getProperty("mail.title");
    }

    @Override
    public List<Fault> analysisAlarm() {
        try {
            Date nowTime=new Date();
            Calendar calendar = Calendar.getInstance();
           
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "pop3");
            props.setProperty("mail.pop3.host", "pop3.163.com");

            Session session = Session.getInstance(props);
            Store store = session.getStore("pop3");
            store.connect("pop3.163.com", USERNAME, AUTH);
            Folder folder = store.getFolder("inbox");
            folder.open(Folder.READ_WRITE);

//            calendar.add(calendar.MINUTE,-5);//获取5分钟前的时间
            calendar.add(calendar.DAY_OF_YEAR,-2);
            Date mindayDate = calendar.getTime();
            //获取最近五分钟的邮件
            SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, mindayDate);
            SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, nowTime);
            SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);
            Message[] messages = folder.search(comparisonAndTerm);

            POP3Folder inbox = (POP3Folder) folder;
            //得到邮件账户的所有邮件信息
            //        Message[] messages = folder.getMessages();
            if (messages.length > 0) {
                for(int i = 0 ; i < messages.length ; i++){
                    MimeMessage msg = (MimeMessage) messages[i];
//                    String id = msg.getMessageID();//获取邮件id   会下载邮件头,比较耗时
                    String uid = inbox.getUID(msg);//获取邮件id 
                    msgSendTime=msg.getSentDate();//获取发送时间
                    //获得邮件主题
                    String subject = msg.getSubject();
                    //获得邮件发件人
                    String from = (messages[i].getFrom()[0]).toString();
                        getMailContent(msg);
                }
            }else{
                logger.info("当前时间无邮件");
            }
            //关闭邮件夹对象
            folder.close(true);
            //关闭连接对象
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

2.获取邮件内容

private  void getMailContent(Part part){
        String contentType = null;
        try {
            contentType = part.getContentType();
            int index = contentType.indexOf("name");//是否为文本类型的附件
            boolean conName = false;
            if(index!=-1){
                conName=true;
            }
            //判断part类型
            if (part.isMimeType("text/html") && ! conName) {
//                System.out.println("----22222------"+(String) part.getContent());
                getTable((String) part.getContent());
            }else if (part.isMimeType("message/rfc822")) {
                getMailContent((Part) part.getContent());
            }else if (part.isMimeType("multipart/*")) {
                Multipart multipart = (Multipart) part.getContent();
                int counts = multipart.getCount();
                for (int i = 0; i < counts; i++) {
                    //递归获取数据
                    getMailContent(multipart.getBodyPart(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3.解析正文表格内容

public void getTable(String s){
        try{
            String tab =s;
            Document doc = Jsoup.parse(tab);
            Elements rows = doc.select("table").get(0).select("tr");
            if (rows.size() > 1) {
                for(int i=1;i<rows.size();i++){
                    Element row = rows.get(i);
                    	System.out.print(row.select("td").get(i).text());
                    }
                }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    ```