I'm trying to send an attachment using JavaMail via Spring 2.5's MailSender, but I keep getting this error:
Passed-in Resource contains an open stream: invalid argument.
JavaMail requires an InputStreamSource that creates a fresh stream for every call.
I am using an InputStreamResource
:
InputStream crofileInputStream = emailDraft.getAttachmentCroFile().getInputStream();
InputStream nacfileInputStream = emailDraft.getAttachmentNacFile().getInputStream();
InputStream sourcefileInputStream = emailDraft.getAttachmentSourceFile().getInputStream();
InputStreamSource[] attachments = {new InputStreamResource(crofileInputStream),new InputStreamResource(nacfileInputStream),new InputStreamResource(sourcefileInputStream)};
sentEmailLog = mailSenderService.sendMIMEMessage(emailDraft, attachmentFileNames, attachments);
this last instruction calls
MimeMessageHelper.addAttachment(fileName,attachments[i])
for each attachment.
Please how could i solve this issue ?
Thanks for you help.
Try to use javax.mail.util.ByteArrayDataSource
String mailTo = message.getHeaders().get("emailAddress", String.class);
MimeMessage mimeMessage = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
ByteArrayDataSource attachment = new ByteArrayDataSource(message.getPayload(), "application/octet-stream");
helper.addAttachment("document.zip", attachment);
helper.setText("text content of the email");
You could also check this example: https://www.javatips.net/api/javax.mail.util.bytearraydatasource
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With