views:

45

answers:

2

Hello ,

I want to parse email messages directly from the filesystem using java (1.6) the email messages will be in a filesystem folder like

abc-12345.msg qwe-23456.msg

and will be in a standard format: for example:

MIME-Version: 1.0
Sender: [email protected]
Received: by 10.239.173.80 with HTTP; Thu, 12 Aug 2010 11:30:50 -0700 (PDT)
Date: Thu, 12 Aug 2010 15:30:50 -0300
Delivered-To: [email protected]
Message-ID: <[email protected]>
Subject: =?ISO-8859-1?Q?Hello_With_Acc=E9=F1ts?=
From: Mr Sender <[email protected]>
To: Mr Recipient <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

This is a testing one

Accent characters:

=E9=F3=FA=F1

Email End

I want to parse this file or use an existing library to parse the file to give me access to the headers / from / to / subject / body and so forth.

The files are all held on a local filesystem. I am no connecting to a message store through pop / imap. What is the easiest, most straightforward way for me to do this. The files may contain attachments.

Any suggestions are very welcome. If there is an existing api (perhaps javamail) that can do this could you please provide examples or references to examples.

Cheers Simon

+1  A: 

use the javamail api:

for example:

  File[] mailFiles = getPertinentMailFiles();
  String host = "host.com";
  java.util.Properties properties = System.getProperties();
  properties.setProperty("mail.smtp.host", host);
  Session session = Session.getDefaultInstance(properties);
  for (File tmpFile : mailFiles) {
     MimeMessage email = null;
     try {
        FileInputStream fis = new FileInputStream(tmpFile);
        email = new MimeMessage(session, fis);
        System.out.println("content type: " + email.getContentType());
        System.out.println("\nsubject: " + email.getSubject());
        System.out.println("\nrecipients: " + Arrays.asList(email.getRecipients(Message.RecipientType.TO))); 
     } catch (MessagingException e) {
        throw new IllegalStateException("illegal state issue", e);
     } catch (FileNotFoundException e) {
        throw new IllegalStateException("file not found issue issue: " + tmpFile.getAbsolutePath() , e); 
     }
  }
Simon B
A: 

You can use JavaMail immediatly for accessing IMAP and POP3-Stores, not for filesystem storage.

In JavaMail the access to email is organzied via implementations of javax.mail.Store. You can check JavaMail API - Third Party Products for implementations of javax.mail.Store for your special file format. Maybe you will implement javax.mail.Store by yourself, if you cannot find something appropriate. With using your Store, you can use all of the features of JavaMail eg attachment handling, all weird MIME stuff etc.

Michael Konietzka