user2365209
user2365209

Reputation: 99

How to get HTML text / plain text from java.mail

When I'm reading email body from java.mail in contentText I get first plain text and after this HTML text. I.e. if send message is

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

contentText will contains:

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

Below is my code to load 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 ?
    }

}

Upvotes: 3

Views: 15597

Answers (1)

Bill Shannon
Bill Shannon

Reputation: 29971

This JavaMail FAQ entry might help.

Upvotes: 5

Related Questions