我想使用java(1.6)直接从文件系统解析电子邮件,电子邮件将在文件系统文件夹中,如
ABC-12345.msg QWE-23456.msg
并将采用标准格式:例如:
MIME-Version: 1.0
Sender: mr.sender@gmail.com
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: mr.recipient@gmail.com
Message-ID: <AANLkTikA-RbE_revkimBCWC2fUrG=t4T47AXq5FTx0vd@mail.gmail.com>
Subject: =?ISO-8859-1?Q?Hello_With_Acc=E9=F1ts?=
From: Mr Sender <mr.sender@gmail.com>
To: Mr Recipient <mr.recipient@gmail.com>
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
我想解析这个文件或使用现有的库来解析文件,以便我可以访问headers / from / to / subject / body等等。
这些文件都保存在本地文件系统中。我没有通过pop / imap连接到消息存储库。对我来说,最简单,最直接的方法是什么?这些文件可能包含附件。
非常欢迎任何建议。如果存在可以执行此操作的现有api(可能是javamail),请提供示例或示例参考。
干杯 西蒙
答案 0 :(得分: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);
}
}
答案 1 :(得分:1)
如果您有电子邮件文本(即整个MIME有效内容),请使用 Mime4J 。
与“javax.mail”相比,该库更易于使用,速度更快,占用空间更小。
答案 2 :(得分:0)
您可以立即使用JavaMail访问IMAP和POP3商店,而不是文件系统存储。
在JavaMail中,通过javax.mail.Store的实现来访问电子邮件。您可以检查JavaMail API - Third Party Products以获取特殊文件格式的javax.mail.Store的实现。如果你找不到合适的东西,也许你会自己实现javax.mail.Store。使用您的商店,您可以使用JavaMail的所有功能,例如附件处理,所有奇怪的MIME内容等。
答案 3 :(得分:0)
// process import emails
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
Store store = null;
Folder folder = null;
File tmpFile = new File("/Users/mugeeshhusain/servers/153232448813.3926.0");
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);
}
boolean success = processMethod(email);