如何从 java.mail 获取 HTML 文本/纯文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18985557/
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
How to get HTML text / plain text from java.mail
提问by user2365209
When I'm reading email body from java.mail in contentTextI get first plain text and after this HTML text. I.e. if send message is
当我在contentText 中从 java.mail 读取电子邮件正文时,我首先得到纯文本,然后是这个 HTML 文本。即如果发送消息是
<div><b>Mock</b><br />Mock 2</div>
<div><b>模拟</b><br />模拟2</div>
contentText will contains:
contentText 将包含:
Mock Mock <div><b>Mock</b><br />Mock 2</div>
Mock Mock <div><b>Mock</b><br />Mock 2</div>
Below is my code to load contentText:
下面是我加载 contentText 的代码:
public void setContentText(Multipart multipart) throws MessagingException, IOException {
contentText ="";
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
getBodyToStringPart(bodyPart);
}
}
protected void getBodyToStringPart(BodyPart bodyPart) throws MessagingException, IOException {
String disposition = bodyPart.getDisposition();
if (!StringUtils.equalsIgnoreCase(disposition, "ATTACHMENT")) {
if (bodyPart.getContent() instanceof BASE64DecoderStream
&& bodyPart.getHeader("Content-ID") != null) {
BASE64DecoderStream base64DecoderStream = (BASE64DecoderStream) bodyPart
.getContent();
byte[] byteArray = IOUtils.toByteArray(base64DecoderStream);
byte[] encodeBase64 = Base64.encodeBase64(byteArray);
this.contentText = this.contentText.replaceAll(
"cid:"
+ bodyPart.getHeader("Content-ID")[0].replaceAll(">", "")
.replaceAll("<", ""), "data:" + bodyPart.getContentType()
+ ";base64," + new String(encodeBase64, "UTF-8"));
} else if (bodyPart.getContent() instanceof MimeMultipart) {
MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent();
for (int j = 0; j < mimeMultipart.getCount(); j++) {
getBodyToStringPart(mimeMultipart.getBodyPart(j));
}
} else {
this.contentText += bodyPart.getContent() + "";
}
} else {
// TODO: Do we need attachments ?
}
}
采纳答案by Bill Shannon
This JavaMail FAQ entrymight help.
这个 JavaMail FAQ 条目可能会有所帮助。