如何使用InputStream和Spring发送带有附件的电子邮件?

问题描述:

情况是这样的:

首先,我们在内存中生成一个文件,我们可以获得 InputStream 对象。
第二个 InputStream 对象必须作为电子邮件的附件发送。语言是Java,我们使用Spring发送电子邮件。

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.

我发现了很多信息,但是我找不到如何使用 InputStream 。我尝试这样做:

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);

但我有一个例外:


传入的资源包含一个开放的流:无效的参数。 JavaMail
需要一个InputStreamSource来为每个
调用创建一个新流。

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


对于在内存中生成的文件,可以使用 ByteArrayResource 。只需使用InputStream 对象commons / io / IOUtils.html rel = noreferrer> IOUtils 来自 Apache Commons IO 库。

For files generated in memory, you may use ByteArrayResource. Just convert your InputStream object using IOUtils from the Apache Commons IO library.

这很简单:

helper.addAttachment("attachement",
new ByteArrayResource(IOUtils.toByteArray(inputStream)));