3
當我從java.mail中讀取電子郵件正文contentText我得到第一個純文本,並在此HTML文本之後。即如果發送的消息是如何從java.mail獲取HTML文本/純文本
<DIV> <b>莫克</B > < BR/>素2 < /格>
contentText將包含:
模擬模擬 <div> <b>模擬</B > < BR/>模擬2 </DIV >
下面是我的代碼加載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 ?
}
}