javamail - 获取邮件正文内容格式错误

时间:2013-01-29 17:42:39

标签: java email formatting javamail mime-message

当我尝试从电子邮件中检索邮件正文时,它会出现半句和奇怪的格式。任何帮助都会很棒......

代码:

protected void dumpPart(Part p) throws MessagingException, IOException
    {
        if (p.isMimeType("text/plain"))
        {
            if (!p.getContent().toString().equals(null))
                System.out.println((String)p.getContent());

        }
        else if (p.isMimeType("multipart/*"))
        {
            Multipart mp = (Multipart)p.getContent();

            for (int x = 0; x < mp.getCount(); x++)
            {
                dumpPart(mp.getBodyPart(x));
            }
        }
    }

输出:

The gist of PNM's protest in RP00-626 is that we shouldn't be able to

charge a transport or fuel fee for our imbalance netting and trading

service.

I aggress with PNM that our tariff language is

vague.

2 个答案:

答案 0 :(得分:1)

我想我看到了问题。

你正在整理信息。

当您使用每个块调用dumpPart时,将使用新行打印出来。所以如果你的消息是chunked链接这个

A: The gist of PNM's protest in RP00-626 is that we shouldn't be able to
B: charge a transport or fuel fee for our imbalance netting and trading
C: service.

然后当你重新组装它时,你会在每个块之后插入新行。

这样做会删除换行符。

protected void dumpPart(Part p, StringBuilder sb) throws MessagingException, IOException
    {
        if (p.isMimeType("text/plain"))
        {
            if (!p.getContent().toString().equals(null))
                sb.append((String)p.getContent());

        }
        else if (p.isMimeType("multipart/*"))
        {
            Multipart mp = (Multipart)p.getContent();

            for (int x = 0; x < mp.getCount(); x++)
            {
                dumpPart(mp.getBodyPart(x), sb);
            }
        }
    }

答案 1 :(得分:1)

我没有看到您的示例输出有问题。它看起来像是分成五行的两个句子,因为它可能在原始文本/普通部分中。原始部件可能具有“text / plain; format = flowed”的Content-Type。在这种情况下,您需要自己实现“format = flowed”的语义(就像您在阅读html部分时那样)。 JavaMail只提供对数据的访问,格式由您决定。