JavaMail需要一个InputStreamSource,为每个调用创建一个新流

时间:2016-11-14 14:09:57

标签: spring javamail

我试图通过Spring 2.5的MailSender使用JavaMail发送附件,但我不断收到此错误:

Passed-in Resource contains an open stream: invalid argument.
JavaMail requires an InputStreamSource that creates a fresh stream for every call.

我使用的是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);

这最后一条指令调用 每个附件MimeMessageHelper.addAttachment(fileName,attachments[i])

请问我该如何解决这个问题?

谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

尝试使用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");

您还可以查看此示例: https://www.javatips.net/api/javax.mail.util.bytearraydatasource