Spring MimeMessageHelper附件文件名编码

时间:2017-07-19 16:47:58

标签: java spring email encoding

我在Spring Boot应用程序中发送带MimeMessageHelper的邮件。

如何告诉它对包含字母 à 的文件名进行编码,以便正确显示?

在构建UTF-8时将编码设置为MimeMessageHelper似乎没有帮助。在Gmail中,生成的附件显示为

=?UTF-8?Q?ex-comp_s.=C3=A0_r.l.?= =?UTF-8?Q?-201\";     filename*1=\"7-07-12_=E2=80=95_2017-07-18

3 个答案:

答案 0 :(得分:0)

我有类似的西里尔文件名下载问题。解决方案是编码文件名(rfc5987):

private static final String CONTENT_DISP_PREFIX = "attachment; filename=";
private static final String CONTENT_DISP_EXTRA_PREFIX = "attachment; filename*=UTF-8''";
private static final String USER_AGENT_FIREFOX = "Firefox";
...
if (!ua.contains(USER_AGENT_FIREFOX)) {
            response.setHeader(CONTENT_DISP_HEADER, CONTENT_DISP_PREFIX + "\"" + encodedFileName + "\"");
        } else {
            response.setHeader(CONTENT_DISP_HEADER, CONTENT_DISP_EXTRA_PREFIX  + encodedFileName );
        }

并以这种方式使用它:

{{1}}

我在这里找到了这个解决方案:http://outofrange.ru/2016/11/encode-non-ascii-filename-content-disposition/

答案 1 :(得分:0)

我用这些方法解决了问题:

  • System.setProperty("mail.mime.splitlongparameters", "false")
  • MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8")
  • MimeUtility.encodeWord(attachmentFilename)

以下是示例代码

System.setProperty("mail.mime.splitlongparameters", "false");
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

// Your email content
helper.setFrom("...");
helper.setTo("...");
helper.setSubject("...");
helper.setText("...");

helper.addAttachment(
    MimeUtility.encodeWord(attachmentFilename),
    attachmentContent
);

答案 2 :(得分:0)

日文文件名有同样的问题,以下步骤修复了它,

MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,  MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, "UTF-8");
//IMP steps
System.setProperty("mail.mime.splitlongparameters", "false");
attachedFileName = MimeUtility.encodeText(attachedFileName, "UTF-8", "Q");
//
helper.addAttachment(attachedFileName, attachmentFile);

没有 Q 选项的 Mimeutility.encodetext 不起作用,如果没有设置 system.setproperty 也不起作用。 这告诉 mimeutility 将字符串编码为带引号的可打印 - 在这里找到了一些东西 - https://stackoverflow.com/a/21575089