如何使用InputStream和Spring发送带有附件的电子邮件? [英] How to send email with attachment using InputStream and Spring?

查看:590
本文介绍了如何使用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.

我发现了很多信息,但是我找不到如何使用<$ c $发送电子邮件附件的方法。 c> 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)));

这篇关于如何使用InputStream和Spring发送带有附件的电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆