首页 > Java > 简单邮件的解析

简单邮件的解析

昨天讲了邮件的发送(这是一个个人笔记,如果有人要参考的话,估计需要做大量的修改才行,但整体逻辑是不会错),既然有发送,肯定会有邮件的解析,那么今天大桥就再写一个例子程序,关于邮件怎么解析。


@Service("parseMailService")
public class ParseMailServiceImpl {

    private static final Logger LOG = LoggerFactory.getLogger(ParseMailServiceImpl.class);

    private static final String[] flagOfMailEnds = {"<DIV><BR></DIV>", "From:<", "From: <", "Sent: ", "Kind regards,",
            "Kind Regards,", "Best regards,", "Best Regards,", "Kind regards,", "Regards,", "Thanks",
            "----- Original Message -----", "> -------------", "---------------"};

    private static final String[] flagOfMailStarts = {"Hi,", "</HEAD>"};

    private static final String[] regExHtmls = {"<[^>]+>", "<[^>]+"};

    @Autowired
    private MailServerService mailServerService;

    public void parseMail() throws Exception {

        LOG.info("==Start parse Mail==");

        Session session = mailServerService.getSession();

        Store store = session.getStore(“pop3”);

        store.connect(MAIL_SERVER_HOST, MAIL_ADDRESS, MAIL_SERVER_PASSWORD);

        Folder folder = store.getFolder("INBOX");

        folder.open(Folder.READ_WRITE);

        Message[] messages = folder.getMessages();

        int mailNo = Integer.parseInt((String) execution.getVariable(SystemConstant.MAIL_NO));

        Message message = messages[mailNo];

        Map<String, String> contents = parseMessage(message);

        message.setFlag(Flags.Flag.DELETED, true);

// message.saveChanges();

        mailServerService.closeConn(folder, store);

        LOG.info("==Mail parse success, this mail from: " + contents.get("user") + "==");

    }

    private String splitContentBySpecialCharacter(String context) {

// Remove mail bottom

        for (String flagOfMailEnd : flagOfMailEnds) {

            int endIndex = context.indexOf(flagOfMailEnd);

            if (endIndex > -1) {

                context = context.substring(0, endIndex);

            }

        }

// Remove mail top

        for (String flagOfMailStart : flagOfMailStarts) {

            int startIndex = context.indexOf(flagOfMailStart);

            if (startIndex > -1) {

                context = context.substring(startIndex + flagOfMailStart.length());

            }

        }

// Filter the HTML tags

        for (String regExHtml : regExHtmls) {

            Pattern p_html = Pattern.compile(regExHtml, Pattern.CASE_INSENSITIVE);

            Matcher m_html = p_html.matcher(context);

            context = m_html.replaceAll("");

        }

        context.replaceAll(" ", "");

// Filter "rn"

        Pattern CRLF1 = Pattern.compile("(rn|r|n|nr){3,}");

        Matcher m1 = CRLF1.matcher(context);

        context = m1.replaceAll("");

        Pattern CRLF = Pattern.compile("(rn|r|n|nr)");

        Matcher m = CRLF.matcher(context);

        context = m.replaceAll(" ");

        return context;

    }

    public Map<String, String> parseMessage(Message message) throws MessagingException, IOException {

        Map<String, String> contents = new HashMap<String, String>();

        StringBuffer content = new StringBuffer(300);

        content = getMailTextContent(message, content);

        contents.put("comment", splitContentBySpecialCharacter(content.toString()));

        return contents;

    }

    public StringBuffer getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {

        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;

        if (part.isMimeType("text/*") && !isContainTextAttach) {

            if (content.length() > 0) {

                content.setLength(0);

            }

            content.append(part.getContent().toString());

        } else if (part.isMimeType("message/rfc822")) {

            getMailTextContent((Part) part.getContent(), content);

        } else if (part.isMimeType("multipart/*")) {

            Multipart multipart = (Multipart) part.getContent();

            int partCount = multipart.getCount();

            for (int i = 0; i < partCount; i++) {

                BodyPart bodyPart = multipart.getBodyPart(i);

                getMailTextContent(bodyPart, content);

            }

        }

        return content;

    }

}


@Service("mailServerService")
public class MailServerServiceImpl implements MailServerService {

    private static final Logger LOG = LoggerFactory.getLogger(MailServerServiceImpl.class);

    @Override
    public Session getSession() {

        Properties props = System.getProperties();
        props.put("mail.smtp.port", 25);
        Session session = Session.getDefaultInstance(props);
        return session;
    }

    @Override
    public void closeConn(Folder folder, Store store) {
        try {
            if (null != folder) {
                folder.close(true);
            }
            if (null != store) {
                store.close();
            }
        } catch (MessagingException e) {
            LOG.error("Close connection fail with mail server", e);
        }

    }
}

全文完,如果本文对您有所帮助,请花 1 秒钟帮忙点击一下广告,谢谢。

作 者: BridgeLi,https://www.bridgeli.cn
原文链接:http://www.bridgeli.cn/archives/29
版权声明:非特殊声明均为本站原创作品,转载时请注明作者和原文链接。
分类: Java 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.

请输入正确的验证码