如何使用InputStream和Spring发送带有附件的电子邮件?
情况是这样的:
首先,我们在内存中生成一个文件,我们可以得到一个InputStream
对象。 其次,InputStream 对象必须作为电子邮件的附件发送。语言是Java,我们使用Spring来发送电子邮件。
我找到了很多信息,但找不到如何使用InputStream
发送电子邮件附件。我尝试这样做:
InputStreamSource iss= new InputStreamResource(new FileInputStream("c:\\a.txt"));
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.addAttachment("attachment", iss);
但我得到一个例外:
传入的资源包含一个开放流:参数无效。 Java邮件 需要一个 InputStreamSource 为每个创建一个新的流 打电话。
The situation is like this:
First, we generate a file in the memory, we can get a InputStream
object.
Second the InputStream object must be send as a attachment of a email. The language is Java, we use Spring to send email.
I have found a lot of information, but I cannot find how to send an email attachment using InputStream
. I try to do like this:
InputStreamSource iss= new InputStreamResource(new FileInputStream("c:\\a.txt"));
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.addAttachment("attachment", iss);
But I get an exception:
Passed-in Resource contains an open stream: invalid argument. JavaMail
requires an InputStreamSource that creates a fresh stream for every
call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于在内存中生成的文件,您可以使用
ByteArrayResource
。只需使用IOUtils
来自 Apache Commons IO 库。这很简单:
For files generated in memory, you may use
ByteArrayResource
. Just convert yourInputStream
object usingIOUtils
from the Apache Commons IO library.It is quite simple:
看看spring参考章节24.3 使用 JavaMail MimeMessageHelper
该示例来自那里,我认为它确实希望您想做:
如果您想使用 Stream,那么您可以使用
而不是文件系统资源
Have a look at the spring reference chapter 24.3 Using the JavaMail MimeMessageHelper
The example is from there, I think it do want you want to do:
if you want to use a Stream, then you can use
instead of FileSystemResource
您可以简单地实现 InputStreamSource 并根据要求在其中传递新的 InputStream:
You can make simple implementation of InputStreamSource and pass fresh InputStream in it, as requested:
工作示例是:
1) Attachment 是一个
InputStreamSource
接口2) Attachment 是一个
DataSource
接口解释:
如果开发人员使用在
isOpen()
方法中返回true
的InputStreamSource
实现,则可能会出现此消息。MimeMessageHelper#addAttacment()
方法中有一个特殊检查:InputStreamResource#isOpen()
始终返回true
,这使得无法使用此实现作为附件:The working examples are:
1) Attachment is an
InputStreamSource
interface2) Attachment is an
DataSource
interfaceThe explanation:
This message could appear if the developer use an implementation of
InputStreamSource
that returntrue
in theisOpen()
method.There is a special check in the method
MimeMessageHelper#addAttacment()
:InputStreamResource#isOpen()
always returntrue
that makes impossible to use this implementation as an attachment://inlineFileObjectCreated -- 您可以创建一个 StringBuilder 对象作为示例
////////////////////////////////////// /////////////////
//inlineFileObjectCreated -- you can create a StringBuilder Object for a example
/////////////////////////////////////////////