The working examples are:
1) Attachment is an InputStreamSource
interface
public void send() throws IOException, MessagingException {
final ByteArrayOutputStream stream = createInMemoryDocument("body");
final InputStreamSource attachment = new ByteArrayResource(stream.toByteArray());
final MimeMessage message = javaMailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject("subject");
helper.setFrom("from@from.com");
helper.setTo("to@to.com");
helper.setReplyTo("replyTo@replyTo.com");
helper.setText("stub", false);
helper.addAttachment("document.txt", attachment);
javaMailSender.send(message);
}
2) Attachment is an DataSource
interface
public void send() throws IOException, MessagingException {
final ByteArrayOutputStream document = createInMemoryDocument("body");
final InputStream inputStream = new ByteArrayInputStream(document.toByteArray());
final DataSource attachment = new ByteArrayDataSource(inputStream, "application/octet-stream");
final MimeMessage message = javaMailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setSubject("subject");
helper.setFrom("from@from.com");
helper.setTo("to@to.com");
helper.setReplyTo("replyTo@replyTo.com");
helper.setText("stub", false);
helper.addAttachment("document.txt", attachment);
javaMailSender.send(message);
}
The explanation:
Passed-in Resource contains an open stream: invalid argument.
JavaMail requires an InputStreamSource that creates a fresh stream for
every call.
This message could appear if the developer use an implementation of InputStreamSource
that return true
in the isOpen()
method.
There is a special check in the method MimeMessageHelper#addAttacment()
:
public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource, String contentType) {
//...
if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) {
throw new IllegalArgumentException(
"Passed-in Resource contains an open stream: invalid argument. " +
"JavaMail requires an InputStreamSource that creates a fresh stream for every call.");
}
//...
}
InputStreamResource#isOpen()
always return true
that makes impossible to use this implementation as an attachment:
public class InputStreamResource extends AbstractResource {
//...
@Override
public boolean isOpen() {
return true;
}
//...
}