Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaMail requires an InputStreamSource that creates a fresh stream for every call

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.

like image 689
R. Piamou Avatar asked Nov 14 '16 14:11

R. Piamou


1 Answers

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

like image 110
Warley Noleto Avatar answered Oct 05 '22 22:10

Warley Noleto