package com.mw.utils;


import com.mw.bean.SmsAlarmLogBean;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FlagTerm;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */
public class MonitorMail {

    public static final String prefix ="[";
    public static final String suffix ="]";

    public static final String regex="\\[([^}]*)\\]";
    public Pattern pattern = Pattern.compile(regex);
    //邮箱服务地址
    private String host;
    //邮箱协议(pop3 imap,协议需要小写)
    private String protocol;
    //服务端口
    private int port;
    //邮箱name
    private String username;
    //邮箱密码
    private String password;

    private URLName url;

    private Session session;

    private Store store;

    private Boolean filter;

    private Folder folder;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



    /**
     *
     * @param protocol 协议
     * @param host 服务器
     * @param port 端口
     * @param username 邮箱账号
     * @param password  邮箱密码
     */
    public MonitorMail(String protocol,String host,int port,String username,String password){

        //协议小写
        this.protocol=protocol.toLowerCase();
        this.host=host;
        this.port=port;
        this.username=username;
        this.password=password;

    }

    /**
     *  初始化连接邮箱服务器
     * @return
     * @throws Exception
     * store.isConnected();
     */

    public MonitorMail initConnect() throws NoSuchProviderException,MessagingException{
        //INBOX 为抓取收件箱的邮件
        this.url = new URLName(protocol, host, port, "INBOX", username, password);
        Properties props = new Properties();
        props.put("mail.imap.timeout",4000);
        props.put("mail.imap.connectiontimeout",4000);//连接超时时间
        this.session = Session.getInstance(props, null);
        //得到邮件仓库
        this.store = session.getStore(url);
        //连接server
        this.store.connect();

        return this;

    }

    /**
     * 获取收件箱所有的信息消息
     * @return
     * @throws Exception
     */
    public Message[] requireMessage() throws Exception{
        this.folder = store.getFolder(url);
        folder.open(Folder.READ_WRITE);
        //index 索引
        FlagTerm ft =
                new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false代表未读,true代表已读
        Message[] message = folder.search(ft);
        return message;

    }


    /**
     * 获取邮箱内容
     * @return
     * @throws Exception
     */
    public List<String> requireText(boolean filter) throws Exception{
        this.filter=filter;
        ArrayList<String>  candidate =new ArrayList<>();
        //获取邮箱内容对象
        Message[] message = requireMessage();

        for(int i=0;i<message.length;i++){
            String text="";
            //文本类型mail
            if (message[i].isMimeType("text/plain")) {

                text = message[i].getContent().toString();
                //媒体类型
            }else if(message[i].isMimeType("multipart/*")){
                text = requireMultipartContext(message[i]);
            }

            //默认拦截器过滤mail 内容
            if(filter){
                String filterContent = defaultFilter(text);
                if(filterContent!=null){
                    candidate.add(filterContent);
                    updateState(message[i]);
                }
            }else {
                String filterContent = customerFilter(text);
                candidate.add(filterContent);
                updateState(message[i]);
            }

        }
        /**
         System.out.println("发件人:" + formatAddress(message.getFrom())
         + "\n发送时间:" + formatDate(message.getSentDate())
         + "\n收件人:" + formatAddress(message.getRecipients(Message.RecipientType.TO))
         //  + "\n收件时间:" + formatDate(msg.getReceivedDate())
         // + "\n抄送:" + formatAddress(msg.getRecipients(Message.RecipientType.CC))
         //                  + "\n暗送:" + formatAddress(msg.getRecipients(Message.RecipientType.BCC))
         + "\n主题:" + message.getSubject());
         **/


        return candidate;
    }

    protected void updateState(Message msg) throws Exception{
        if(protocol.equals("imap")) {
            //pop3没有判断邮件是否为已读的功能,要使用imap才可以进行邮件的标记状态
            msg.setFlag(Flags.Flag.SEEN, true);//设置邮件为已读状态
           // msg.saveChanges();
        }
    }

    /**
     * 获取Multipart/*类型的邮箱内容
     * @param message
     * @return
     */
    public String requireMultipartContext(Message message) throws Exception{
        StringBuffer strBuf =new StringBuffer();
        if (message.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) message.getContent();
            int count = mp.getCount();
            for (int j = 0; j < count; j++) {
                BodyPart bp = mp.getBodyPart(j);
                String disposition = bp.getDisposition();
                if (disposition != null && disposition.equals(Part.ATTACHMENT)) {
                    System.out.println("附件:" + bp.getFileName());
                } else {
                    if (bp.isMimeType("text/plain")) {
                        //邮件文本内容
                        strBuf.append(bp.getContent());

                    }
                }
            }
        }
        return strBuf.toString();
    }



    /**
     * 默认拦截,匹配"[][][][]" 此类型格式的mail
     * @param mailContent
     * @return 匹配失败返回null
     */
    protected String defaultFilter(String mailContent){
        StringBuffer buffer =new StringBuffer();
        Matcher matcher = pattern.matcher(mailContent);
        while(matcher.find()){
            buffer.append(matcher.group());
        }
        String content = buffer.toString();
        if(content.length()==0){
            return null;
        }
        return content;
    }


    /**
     * 解析mail 内容
     * @param content
     * @return
     */
    public   SmsAlarmLogBean defaultParseText(String content){
        if(!filter){
            throw new IllegalStateException("只可以解析[][][]格式的邮件内容");
        }
        String[] info = content.split(suffix);
        SmsAlarmLogBean alarm =null;
        if(info.length>7){
            alarm=   new SmsAlarmLogBean();
            alarm.setAlarm_type(preIndex(info[5]));
            alarm.setServer_name(preIndex(info[0]));
            alarm.setPc_ip(preIndex(info[1]));
            alarm.setStart_time(preIndex(info[3]));
            alarm.setProcess_name(preIndex(info[7]));
            alarm.setEquip_name(preIndex(info[4]));

        }
        return alarm;
    }

    /**
     * 自定义拦截器
     */
    public String customerFilter(String mailContent){


        return mailContent;
    }

    /**
     * 自定义解析
     * @param content
     * @return
     */
    public   Object customerParseText(String content){
        return null;
    }


    public static String preIndex(String info){
        String substring ="";
        if(info.length()>=2) {
            substring= info.substring(1);
        }
        return substring;
    }

   public void close()throws Exception{
        if(folder !=null) {
            if (folder.isOpen()) {
                folder.close(true);
            }
        };
        if(store!=null){
            if(store.isConnected()){
                store.close();
            }
        }


    }

    public static String formatDate(Date date) {
        return sdf.format(date);
    }

    public static String formatAddress(Address[] addr) {
        StringBuffer sb = new StringBuffer();
        if (addr == null) {
            return "";
        }
        for (int i = 0; i < addr.length; i++) {
            Address a = addr[i];
            if (a instanceof InternetAddress) {
                InternetAddress ia = (InternetAddress) a;
                sb.append(ia.getPersonal() + "<" + ia.getAddress() + ">,");
            } else {
                sb.append(a.toString());
            }
        }
        if (sb.length() != 0) {
            return sb.substring(0, sb.length() - 1);
        }
        return "";
    }

    //test MonitorMail
    public static void main(String[] args) throws Exception {
        MonitorMail mail =new MonitorMail("imap","192.168.0.101",143,"test@luobin.com",
                "Pass1234");
        List<String> strings = mail.initConnect().requireText(true);//fasle返回我们自定义的,根据业务需求
        System.out.println(strings);
        mail.close();


    }



}

 

posted on 2019-04-11 14:12  iscys  阅读(409)  评论(0编辑  收藏  举报