Total Pageviews

2016/08/04

[JavaMail] Attachment name does not show correctly in Email

Problem
I am using JavaMail API to send email. But the attachment name does not show correctly.
The name should be 退匯明細表.pdf‎, but I got ATT97145.pdf‎.

The incorrect email looks like:


The expected email looks like:


Here is the code snippet to add attachment in email:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private void attachFiles(MimeMessageHelper messageHelper, List<File> attachFiles)
        throws MessagingException {
    for (File attachFile : attachFiles) {
        FileSystemResource file = new FileSystemResource(attachFile);
        log.info("attachFile.getName():" + attachFile.getName());

        try {
            messageHelper.addAttachment(attachFile.getName(), file);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}


Solution
You can utilize MimeUtility.encodeText to handle the file name.
Here is the updated code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
private void attachFiles(MimeMessageHelper messageHelper, List<File> attachFiles)
        throws MessagingException {
    for (File attachFile : attachFiles) {
        FileSystemResource file = new FileSystemResource(attachFile);
        log.info("attachFile.getName():" + attachFile.getName());

        try {
            messageHelper.addAttachment(
                    MimeUtility.encodeText(attachFile.getName(), "UTF-8", null), file);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}


Reference
[1] http://docs.oracle.com/javaee/6/api/javax/mail/internet/MimeUtility.html#encodeText(java.lang.String, java.lang.String, java.lang.String)

No comments: