2

我正在开发需要在 Java 中获取邮件正文内容的应用程序。当文本是纯文本时,我可以毫无问题地将其作为字符串。但是当邮件内容包含粗体字母时,例如:

主题:转发:转发:回复:在区块链/加密货币应用程序上工作的机会!

此文本实际上打印为:

%0D%0ASubject%3A Re%3A 有机会在区块链 %2F 加密货币上工作%0D%0AApplication%21%21%

我没有任何理由这样做。

这是我从邮件中获取内容的简单代码:

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;
    }

第二种方法:

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;
    }

有关如何解决相同问题的任何帮助?

4

0 回答 0