Skip to content

MimeMessageHelper does not handle attachment file name encoding [SPR-9258] #13896

@spring-projects-issues

Description

@spring-projects-issues

Anton Kuzmin opened SPR-9258 and commented

MimeMessageHelper.addAttachment should encode file name according to RFC 822. As MimeBodyPart javadoc says:
A note on RFC 822 and MIME headers
RFC 822 header fields must contain only US-ASCII characters. MIME allows non ASCII characters to be present in certain portions of certain headers, by encoding those characters. RFC 2047 specifies the rules for doing this. The MimeUtility class provided in this package can be used to to achieve this. Callers of the setHeader, addHeader, and addHeaderLine methods are responsible for enforcing the MIME requirements for the specified headers. In addition, these header fields must be folded (wrapped) before being sent if they exceed the line length limitation for the transport (1000 bytes for SMTP). Received headers may have been folded. The application is responsible for folding and unfolding headers as appropriate.

Workaround is instead of calling MimeMessageHelper.addAttachment do this:
ByteArrayDataSource content = new ByteArrayDataSource(attachment.getContent());
// helper.addAttachment(attachment.getFileName(), content);
Assert.notNull(fileName, "Attachment filename must not be null");
Assert.notNull(content, "DataSource must not be null");
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);

    String fileName = null;
    try {
      fileName = MimeUtility.encodeText(fileName);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }

    mimeBodyPart.setFileName(fileName);
    mimeBodyPart.setDataHandler(new DataHandler(content));
    helper.getRootMimeMultipart().addBodyPart(mimeBodyPart);

Affects: 2.5.6

Backported to: 3.1.4

Metadata

Metadata

Assignees

Labels

status: backportedAn issue that has been backported to maintenance branchestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions