如何从java.mail获取HTML文本/纯文本

时间:2013-09-24 15:18:07

标签: java javamail

当我从 contentText 中的java.mail中读取电子邮件正文时,我得到第一个纯文本,并在此HTML文本之后。即如果发送消息是

  

< div>< b> Mock< / b>< br /> Mock 2< / div>

contentText将包含:

  模拟模拟   < div>< b> Mock< / b>< br /> Mock 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 ?
    }

}

1 个答案:

答案 0 :(得分:4)

This JavaMail FAQ entry可能会有所帮助。