How to read text inside body of mail using javax.mail

This answer extends yurin’s answer. The issue he brought up was that the content of a MimeMultipart may itself be another MimeMultipart. The getTextFromMimeMultipart() method below recurses in such cases on the content until the message body has been fully parsed.

private String getTextFromMessage(Message message) throws MessagingException, IOException {
    if (message.isMimeType("text/plain")) {
        return message.getContent().toString();
    } 
    if (message.isMimeType("multipart/*")) {
        MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
        return getTextFromMimeMultipart(mimeMultipart);
    }
    return "";
}

private String getTextFromMimeMultipart(
        MimeMultipart mimeMultipart)  throws MessagingException, IOException{
    String result = "";
    for (int i = 0; i < mimeMultipart.getCount(); i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            return result + "\n" + bodyPart.getContent(); // without return, same text appears twice in my tests
        } 
        result += this.parseBodyPart(bodyPart);
    }
    return result;
}

private String parseBodyPart(BodyPart bodyPart) throws MessagingException, IOException { 
    if (bodyPart.isMimeType("text/html")) {
        return "\n" + org.jsoup.Jsoup
            .parse(bodyPart.getContent().toString())
            .text();
    } 
    if (bodyPart.getContent() instanceof MimeMultipart){
        return getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
    }

    return "";
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)