How to get various type of content of mail as it is in Java?

202 Views Asked by At

I am working on application where I need to get content of mail body as it is in Java. When text is plain, I have no issue to get is as a string. But when mail content contains bold letters like:

Subject: Fwd: Fwd: Re: Opportunity to work on Block-chain / Crypto Currency Application!!

This text actually get printed as:

%0D%0ASubject%3A Re%3A Opportunity to work on Block-chain %2F Crypto Currency%0D%0AApplication%21%21%

I am not getting any reason for this.

Here is my simple code to get the content from mail:

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

Second method:

private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
        String result = "";
        int count = mimeMultipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            //if the body part is a text file, don't consider it as part of mail content(body) to print in the comment
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
            if (bodyPart.isMimeType("text/plain")) {
                result = result + "\n" + bodyPart.getContent().toString();
                break; // without break same text appears twice in my tests
            } else if (bodyPart.isMimeType("text/html")) {
                String html = (String) bodyPart.getContent();
                /// result = result + "\n" + org.Jsoup.parse(html).text();
            } else if (bodyPart.getContent() instanceof MimeMultipart) {
                result = result + getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
            }
        }
    }
        return result;
    }

Any help on how I can fix the same?

0

There are 0 best solutions below