Spring: MimeMessageHelper encoding for attachments

2.9k views Asked by At

In Spring there is an option to set the encoding for mailing:

MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

This works great for subject and message of the email.

However if there is an attachment, the default encoding of the JVM will be used and specified in the Content-Type of the attachment part of the email (even if specifying encoding globally in the application and/or through arguments while deploying the jar).

Has anybody managed to tell Spring to use a specific encoding for mail attachments also? I know there is a way of doing it by using this structure:

messageHelper.addAttachment(filename, new InputStreamSource() {
    @Override
    public InputStream getInputStream () throws IOException {
        return file.getInputStream();
        }
    }, "text/plain; charset=UTF-8");

The problem with this is that now I have to manually describe every attachment type and encoding. If there is no other way, then I guess this is the only way to go.

1

There are 1 answers

0
Deniss M. On BEST ANSWER

In the end this is how I solved it (not the cleanest way, but works ok):

private String determineContentType(String fileName) {
        String contentType;

        if (fileName.contains(".txt")) {
            contentType = "text/plain; charset=" + mailProperties.getEncoding();
        }
        else if (fileName.contains(".xls")) {
            contentType = "application/vnd.ms-excel; charset=" + mailProperties.getEncoding();
        }
        else if (fileName.contains(".pdf")) {
            contentType = "application/pdf; charset=" + mailProperties.getEncoding();
        }
        else if (fileName.contains(".doc")) {
            contentType = "application/msword; charset=" + mailProperties.getEncoding();
        }
        else if (fileName.contains(".xml")) {
            contentType = "text/xml; charset=" + mailProperties.getEncoding();
        }
        else if (fileName.contains(".zip")) {
            contentType = "application/zip; charset=" + mailProperties.getEncoding();
        }
        else {
            contentType = "text/plain; charset=" + mailProperties.getEncoding();
        }
        return contentType;
    }