Affects: spring-context-support-6.1.12


I'm creating a mail using MimeMessageHelper. I want to add inline file using ByteArrayResource.

The function used is :

public void addInline(String contentId, Resource resource) throws MessagingException {
        Assert.notNull(resource, "Resource must not be null");
        String contentType = getFileTypeMap().getContentType(resource.getFilename());
        addInline(contentId, resource, contentType);
    }

The problem is that org.springframework.core.io.ByteArrayResource extends org.springframework.core.io.AbstractResource which implements getFilename() returning null

       /**
     * This implementation always returns {@code null},
     * assuming that this resource type does not have a filename.
     */
    @Override
    @Nullable
    public String getFilename() {
        return null;
    }

So

String contentType = getFileTypeMap().getContentType(resource.getFilename());

throw a java.lang.NullPointerException because jakarta.activation.MimetypesFileTypeMap.getContentType(String filename) code start with :

 public synchronized String getContentType(String filename) {
        int dot_pos = filename.lastIndexOf("."); // period index

(jakarta.activation-api.2.1.3)

The thrown trace is

Caused by: java.lang.NullPointerException: Cannot invoke "String.lastIndexOf(String)" because "filename" is null
    at jakarta.activation.MimetypesFileTypeMap.getContentType(MimetypesFileTypeMap.java:361)
    at org.springframework.mail.javamail.ConfigurableMimeFileTypeMap.getContentType(ConfigurableMimeFileTypeMap.java:180)

Comment From: bclozel

I think this is the expected behavior here, since you are providing a Resource implementation that doesn't provide a filename. Can you choose a different Resource implementation or create your own?

Comment From: blink38

I managed to work around creating my own resource implementation. A simple solution is to create a class extending ByteArrayResource which override getFilename().

But, I think it should be great the developer to be advertise of this behaviour when writing code (maybe a note in the addInline comment) instead of discover it when debugging a NullPointerException.

Comment From: bclozel

In the end I have processed it as a bug, since we should fall back to "application/octet-stream" (as it is the case already in other places) instead of failing with a NPE. Thanks for your report!