bbottema/simple-java-mail

URLDataSource uses source data name

ben-manes opened this issue · 5 comments

When adding at attachment from a URL source (e.g. a pdf on S3) the name of the attachment is not honored. Instead of the specified name, the file name of the resource is used. The workaround is simple - wrap using a named datasource. Something simple like the following worked for me,

private static final class NamedDataSource implements DataSource {
  private final DataSource delegate;
  private final String name;

  NamedDataSource(String name, DataSource delegate) {
    this.delegate = requireNonNull(delegate);
    this.name = requireNonNull(name);
  }

  @Override public String getName() {
    return name;
  }
  @Override public String getContentType() {
    return delegate.getContentType();
  }
  @Override public InputStream getInputStream() throws IOException {
    return delegate.getInputStream();
  }
  @Override public OutputStream getOutputStream() throws IOException {
    return delegate.getOutputStream();
  }
}

Can you provide some example code where this happens?

MimeMessageHelper#getBodyPartFromDatasource is pretty clear. If dataSource.getName() returns null or empty then it uses the name specified in the Attachment. Otherwise it uses the source resource's name.

I imagine any test code I show you won't be too insightful beyond the above, as my usage is pretty benign (thanks to your clean api). To reproduce you can add an attachment like,

URL url = new URL("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
email.addAttachment("logo.png", new URLDataSource(url));

and the email will have a file named googlelogo_color_272x92dp.png instead of logo.png.

I've been refactoring this part for the past hour and I think it will be solved now with the next release.

/edit just tested your case which was working correctly now.

Thanks! 👍

Released in v4.1.0.