LoginSignup
2
1

More than 5 years have passed since last update.

Spring Boot メールで添付のファイル名が文字化けしたのでその対策

Posted at

メールの添付ファイルが文字化けする

org.springframework.boot:spring-boot-starter-mail

Web上にもQiitaにも沢山あるSpringのメール送信方法を使って添付ファイルを送信してみたら、添付ファイル名が見事に文字化けしていました。
Screen Shot 2019-04-01 at 08.00.21.png

どうやらファイル名が日本語のみの場合はOKですが、ファイル識別子が入ったりするとこの文字化けが起こるようです(ここは詳しく調査していない)


    private void sendMail(File file) throws MessagingException, URISyntaxException, IOException {
        JavaMailSender sender = this.getMailSender();

        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.name());

        String toAddr = this.mailToAddr;
        helper.setTo(toAddr);

        // 複数CCアドレスに対応(カンマ区切り)
        if (!StringUtils.isEmpty(this.mailCcAddrs)) {
            String[] ccAddrArr = this.mailCcAddrs.split(",");
            helper.setTo(ccAddrArr);
        }
        String subject = "テストメールです"; 
        helper.setSubject(subject);

        // メール本文テンプレ取得
        Path path = Paths.get(getClass().getClassLoader()
                .getResource("mail_template.txt").toURI());

        Stream<String> lines = Files.lines(path);
        String template = lines.collect(Collectors.joining("\n"));
        String body = template.replace("[[Replace]]", toAddr);
        lines.close();
        helper.setText(body);

        // ファイル添付
        helper.addAttachment("添付ファイルの名称です 添付は template.txt", file);

        sender.send(message);
    }

以下の点を修正

添付ファイルのファイル名を一旦加工する

MimeUtility.encodeWord("ファイル名");

Screen Shot 2019-04-01 at 07.59.36.png

システムプロパティにメールの設定を追加する

最初の MimeMessage インスタンス作成の前にこのプロパティを変更しておく

System.setProperty("mail.mime.splitlongparameters", "false");

Screen Shot 2019-04-01 at 07.59.20.png

上記修正後のファイル名を確認

Screen Shot 2019-04-01 at 08.00.06.png

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1