Java Email message Parser?

大憨熊 提交于 2019-11-27 03:44:52
Jherico

JavaMail is 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 Email library for mail handling.

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

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

I have had problems with JavaMail (it fails to parse some email messages that it should).

I have had much better results with Mime4J.

I would suggest you use 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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!