Issue
I'm trying to send an attachment using JavaMail via Spring 3's MailSender, but I keep getting this error:
org.springframework.mail.MailPreparationException: Could not prepare mail; nested exception is java.lang.IllegalArgumentException: Passed-in Resource contains an open stream: invalid argument. JavaMail requires an InputStreamSource that creates a fresh stream for every call.
I've found and followed others' advice on this (e.g., how to use spring send email with attachment use InputStream?), but can't figure out why my InputStream
would be open. I've tried a couple of different variations to create the InputStreamSource
for the attachment (which is a String
) and had the same problem with both approaches.
approach 1:
message.addAttachment(
filenameBase + "_" + DATE_FORMAT.format(new Date()) + ".csv",
new InputStreamSource() {
@Override
public InputStream getInputStream() throws IOException {
return IOUtils.toInputStream(content);
}
});
approach 2:
message.addAttachment(
filenameBase + "_" + DATE_FORMAT.format(new Date()) + ".csv",
new ByteArrayResource(content.getBytes()));
Solution
In the end it looks like this wasn't the problem - there was another attachment call that wasn't using InputStreamSource correctly (which seems a bit weird as the line numbers were lining up with this one)...
Answered By - gdmitchell
Answer Checked By - David Goodson (JavaFixing Volunteer)