Java电子邮件解析器

时间:2011-09-12 06:27:46

标签: java parsing email

我必须解析这样的电子邮件,并找出正文,日期等。任何帮助都将不胜感激。

Date:        XXXXX
Reply-To:     XXXXX
Sender:       XXXXX
From:        XXXX
Subject:     Test
In-Reply-To:  XXXX
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary="=__Part416ABDAE.0__="
=__Part416ABDAE.0__=
 Content-Type: text/plain; charset=US-ASCII
 Content-Transfer-Encoding: quoted-printable
Test

2 个答案:

答案 0 :(得分:2)

这是一个正则表达式解决方案:

import java.util.regex.*;

class Test {

    public static void main(String[] args) {

        String input = "Date:        XXXXX\n"
                     + "Reply-To:     XXXXX\n"
                     + "Sender:       XXXXX\n"
                     + "From:        XXXX\n"
                     + "Subject:     Test\n"
                     + "In-Reply-To:  XXXX\n"
                     + "Mime-Version: 1.0\n"
                     + "Content-Type: multipart/alternative; " +
                                 "boundary=\"=__Part416ABDAE.0__=\"";

        Pattern p = Pattern.compile("(.*?):\\s+(.*)");
        Matcher m = p.matcher(input);
        while (m.find()) {
            System.out.println("Key: " + m.group(1));
            System.out.println("Val: " + m.group(2));
            System.out.println();
        }
    }
}

<强>输出:

Key: Date
Val: XXXXX

Key: Reply-To
Val: XXXXX

Key: Sender
Val: XXXXX

Key: From
Val: XXXX

Key: Subject
Val: Test

Key: In-Reply-To
Val: XXXX

Key: Mime-Version
Val: 1.0

Key: Content-Type
Val: multipart/alternative; boundary="=__Part416ABDAE.0__="

答案 1 :(得分:0)

如果您认真解析电子邮件(这不是家庭作业解析任务),您应该查看 Mime4J