2010-08-12 52 views
2

我想从文件系统使用Java直接解析电子邮件(1.6)的电子邮件将文件系统中的文件夹一样读/解析电子邮件/与Java邮件直接从标准RFC邮件格式的文件系统

ABC -12345.msg QWE-23456.msg

,并会在标准格式:如:

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 

我要分析此文件,或使用现有的库来解析该文件给我访问标题/从/到/主题/身体等等。

这些文件都保存在本地文件系统上。我没有通过pop/imap连接到消息存储。什么是我最简单,最直接的方式来做到这一点。这些文件可能包含附件。

任何建议都非常欢迎。如果有一个现有的api(也许是javamail)可以做到这一点,请提供示例或参考。

干杯 西蒙

回答

4

使用JavaMail API:

例如:

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

您可以使用JavaMail立刻访问IMAP和POP3-商店,而不是文件系统存储。

在JavaMail中,通过javax.mail.Store的实现组织了对电子邮件的访问。您可以检查JavaMail API - Third Party Products以获取特殊文件格式的javax.mail.Store的实现。也许你会自己实现javax.mail.Store,如果你找不到合适的东西。用你的商店,你可以如果你有电子邮件文本(即整个MIME有效载荷),比我会用Mime4J使用所有的JavaMail的如附件处理功能,所有怪异的MIME东西等

1

该库比“javax.mail”更容易使用,速度更快,占用空间更小。