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

问题描述 投票:1回答:1

我试图通过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])

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

谢谢你的帮助。

spring javamail
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.