邮件添加Multipart附件文件名乱码的解决办法

 调用以下createMultipartFromFile方法返回Multipart类型作为附件,part.setName设置了各种各样的格式,最终都是中文乱码,最终使用了下面的encodeFileName方法返回的格式文件名成功显示中文

   

Multipart part = createMultipartFromFile(file); // 将文件转换为 Multipart 对象
 /*文件添加到附件*/
    private static Multipart createMultipartFromFile(File file) throws IOException {
        Path path = Paths.get(file.toURI());
        byte[] fileContent = Files.readAllBytes(path);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(bos, StandardCharsets.UTF_8);
        osw.write(new String(fileContent, StandardCharsets.UTF_8));
        osw.flush();
        bos.flush();
        Multipart part = new Multipart();
        part.setContent(Base64.getEncoder().encodeToString(bos.toByteArray()));

        part.setName(encodeFileName(file.getName())); //上面将附件名设置成UTF-8再设置给邮件附件名
        part.setEncoding("BASE64"); //设置附件的正确解码
        return part;
    }

 private static String encodeFileName(String fileName) throws UnsupportedEncodingException {
        byte[] fileNameBytes = fileName.getBytes(StandardCharsets.UTF_8);
        boolean needsEncoding = false;
        for (byte b : fileNameBytes) {
            if ((b & 0x80) != 0) {
                needsEncoding = true;
                break;
            }
        }
        if (needsEncoding) {
            return "=?UTF-8?B?" + Base64.getEncoder().encodeToString(fileNameBytes) + "?=";
        } else {
            return fileName;
        }
    }

注意: 如果调用以上两个方法出现邮件中附件打开提示已损坏的提示,那么就把第一个方法修改成以下(也就是直接转Base64编码,而不是先转UTF-8再去转Base64):

/*文件添加到附件*/
    private static Multipart createMultipartFromFile(File file) throws IOException {
        Path path = Paths.get(file.toURI());
        byte[] fileContent = Files.readAllBytes(path);

        // 直接对二进制文件内容进行Base64编码
        String encodedFileContent = Base64.getEncoder().encodeToString(fileContent);

        Multipart part = new Multipart();
        part.setContent(encodedFileContent);
        part.setName(encodeFileName(file.getName()));
        part.setEncoding("BASE64");
        return part;
    }

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往事不堪回首..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值