Take the 2-minute tour ×

I have to parse the email message like this and figure out the body,date etc.Any help would be appreciated.

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__="
 Content-Transfer-Encoding: quoted-printable
share|improve this question
Is this homework? If so, please show how far you've got and where you're running into problems. If not, is there any reason you're not using an existing library? –  Jon Skeet Sep 12 '11 at 6:30
Google for Java Mail API... unless this is homework and you have to write a parser... in which case please tag this correctly. –  Jim Garrison Sep 12 '11 at 6:32
I have those email messages in file (txt) format extracted from mail server.So would java mail API work there? Also it has html also inside that –  Neeha Sep 12 '11 at 6:45
add comment

2 Answers

Here's a regex solution:

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; " +

        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));


Key: Date

Key: Reply-To

Key: Sender

Key: From

Key: Subject
Val: Test

Key: In-Reply-To

Key: Mime-Version
Val: 1.0

Key: Content-Type
Val: multipart/alternative; boundary="=__Part416ABDAE.0__="
share|improve this answer
thanks for the solution.Actually I am looking for is I have email extracts in a text file format and I have to run parser for those.It has also some messages in html format. –  Neeha Sep 12 '11 at 6:44
if you edit your question and elaborate I might be able to elaborate my answer. –  aioobe Sep 12 '11 at 7:00
Use a new Scanner(new File("your_file.txt")) and do Matcher m = p.matcher(scanner.nextLine()) inside the loop. (And go on until !scanner.hasNext. Let me know if you need further instructions. –  aioobe Sep 12 '11 at 7:32
Thanks .I m trying to paste the content but this is not taking.Is there any way I can attach file to it? –  Neeha Sep 12 '11 at 7:47
No. Use paste-bin if you like. –  aioobe Sep 12 '11 at 7:47
show 3 more comments

If your serious about parsing email (and this is not a home work parsing assignment) you should look at Mime4J.

share|improve this answer
add comment

Your Answer


