Java电子邮件消息解析器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3444660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Email message Parser?
提问by Kareem
Is anyone familiar with a Java library that helps with parsing the fields (date, subject, from, to) of the email below?
是否有人熟悉有助于解析以下电子邮件字段(日期、主题、发件人、收件人)的 Java 库?
Message-ID: <19815303.1075861029555.JavaMail.ss@kk>
Date: Wed, 6 Mar 2010 12:32:20 -0800 (PST)
From: [email protected]
To: [email protected]
Subject: some subject
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-From: one, some <[email protected]>
X-To: one
X-cc:
X-bcc:
X-Folder: Bob\Inbox
X-Origin: Bob-R
X-FileName: rbob (Non-Privileged).pst
some message
采纳答案by Jherico
JavaMailis an oracle library that provides mail services and mail related services (like parsing conventional & MIME messages) in the javax.mail package. Additionally Apache has a Commons Emaillibrary for mail handling.
JavaMail是一个 oracle 库,它在 javax.mail 包中提供邮件服务和邮件相关服务(如解析常规和 MIME 消息)。此外,Apache 有一个用于邮件处理的Commons Email库。
In the JavaMail api, a simple way to parse a string containing an email message (which may or may not be explicitly MIME) would be as follows
在 JavaMail api 中,解析包含电子邮件消息(可能是也可能不是明确的 MIME)的字符串的简单方法如下
String content = ...
Session s = Session.getInstance(new Properties());
InputStream is = new ByteArrayInputStream(content.getBytes());
MimeMessage message = new MimeMessage(s, is);
and parsing the headers could be done like this
并且可以像这样解析标题
message.getAllHeaderLines();
for (Enumeration<Header> e = message.getAllHeaders(); e.hasMoreElements();) {
Header h = e.nextElement();
h.getName();
h.getValue();
}
回答by Adam Gent
回答by Ashish Sharma
I would suggest you use email-mime-parser,
我建议你使用email-mime-parser,
Following sample code gives you all the relevant info you need:
以下示例代码为您提供了所需的所有相关信息:
ContentHandler contentHandler = new CustomContentHandler();
MimeConfig mime4jParserConfig = new MimeConfig();
BodyDescriptorBuilder bodyDescriptorBuilder = new DefaultBodyDescriptorBuilder();
MimeStreamParser mime4jParser = new MimeStreamParser(mime4jParserConfig,DecodeMonitor.SILENT,bodyDescriptorBuilder);
mime4jParser.setContentDecoding(true);
mime4jParser.setContentHandler(contentHandler);
InputStream mailIn = 'Provide email mime stream here';
mime4jParser.parse(mailIn);
Email email = ((CustomContentHandler) contentHandler).getEmail();
List<Attachment> attachments = email.getAttachments();
Attachment calendar = email.getCalendarBody();
Attachment htmlBody = email.getHTMLEmailBody();
Attachment plainText = email.getPlainTextEmailBody();
String to = email.getToEmailHeaderValue();
String cc = email.getCCEmailHeaderValue();
String from = email.getFromEmailHeaderValue();