如何使用弹簧发送附件使用InputStream的电子邮件?

kak*_*008 28 java email spring inputstream

情况是这样的:

首先,我们在内存中生成一个文件,我们可以得到一个InputStream对象,InputStream对象必须作为电子邮件的附件发送...语言是java,我们使用spring发送电子邮件.

我发现很多,但我找不到如何发送电子邮件附件使用InputStream ...我尝试这样做:

InputStreamSource iss = null;
                    iss = new InputStreamResource(new FileInputStream("c:\\a.txt"));
MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
                        true, "UTF-8");
message.addAttachment("attachment", iss);
Run Code Online (Sandbox Code Playgroud)

但我们例外:

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

小智 54

对于在内存中生成的文件,您可以使用ByteArrayResource.只需使用Apache Commons的IOUtils转换您的InputStream对象.这很简单:

    helper.addAttachment("attachement",
    new ByteArrayResource(IOUtils.toByteArray(inputStream)));
Run Code Online (Sandbox Code Playgroud)


Ral*_*lph 6

看看Spring参考章节24.3使用JavaMail MimeMessageHelper

这个例子来自那里,我认为它确实想要你做:

JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com");

MimeMessage message = sender.createMimeMessage();

// use the true flag to indicate you need a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo("test@host.com");

helper.setText("Check out this image!");

// let's attach the infamous windows Sample file (this time copied to c:/)
FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg"));
helper.addAttachment("CoolImage.jpg", file);

sender.send(message);
Run Code Online (Sandbox Code Playgroud)