如何在使用 Java Mail API 时转换文件名



我在SQL数据库和邮件服务器之间编写了一个适配器。我使用了 POP3 连接。此后,我遇到了以下问题 - 当适配器收到俄语文件名时,会发生此错误。

示例输入文件名:=?UTF-8?B?0KHQutGA0LjQv9C60LAg0JzQsNGA0LjRjy5kb2N4?=
编码格式为 Base64。我试图将 Base64 转换为 UTF-8,但它没有解决问题。

我的代码:

if (contentType.contains("multipart"))
            {
                Multipart multiPart = (Multipart) message.getContent();
                int numberOfParts = multiPart.getCount();
                for (int partCount = 0; partCount<numberOfParts; partCount++)
                {
                    MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
                    {
                        //this part is attachment
                        continue;
                    }
                        //String fileName = part.getFileName();
                        String fileName = part.getFileName().toString();
                        if (fileName.contains("UTF-8"))
                        {
                            byte[] decoded = Base64.decodeBase64(fileName.getBytes());
                            fileName = new String(decoded, "UTF-8");
                        }
                        attachFiles += fileName + ", ";
                        part.saveFile("d:/" + File.separator + fileName);
                        //this part may be the message content
                        messageContent = part.getContent().toString();
                }
                if (attachFiles.length() > 1)
                {
                    attachFiles = attachFiles.substring(0, attachFiles.length()-2);
                }
            }

有人知道我如何解决这个问题吗?

文件名

不是base64编码的字符串。它按照 RFC 2047 的定义进行编码。

不要尝试手动解码此类字符串。使用像Apache Mime4j这样的可靠库来编码/解码MIME消息。

将 Mime4j 添加到您的项目中(此处为 Maven):

<dependency>
    <groupId>org.apache.james</groupId>
    <artifactId>apache-mime4j-core</artifactId>
    <version>0.7.2</version>
</dependency>

使用 org.apache.james.mime4j.codec.DecoderUtil 解码带引号的可打印字符串:

@Test
public void test() {
    String decoded = DecoderUtil.decodeEncodedWords("=?UTF-8?B?0KHQutGA0LjQv9C60LAg0JzQsNGA0LjRjy5kb2N4?=", null);
    assertEquals("Скрипка Мария.docx", decoded);
}

最新更新