Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send email with attachment using InputStream and Spring?

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.

like image 571
kaka2008 Avatar asked Apr 15 '11 13:04

kaka2008


People also ask

How can I send multiple attachments by email in Java?

The body must be of type Multipartfor containing attachments. The Multipart object holds multiple parts in which each part is represented as a type of BodyPart whose subclass, MimeBodyPart – can take a file as its content. message. setContent(multipart);


2 Answers

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

It is quite simple:

helper.addAttachment("attachement", new ByteArrayResource(IOUtils.toByteArray(inputStream))); 
like image 73
ptr07 Avatar answered Sep 25 '22 21:09

ptr07


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:

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("[email protected]");  helper.setText("Check out this image!");  // let's attach the infamous windows Sample file (this time copied to c:/) FileSystemResource resource = new FileSystemResource(new File("c:/Sample.jpg"));  helper.addAttachment("CoolImage.jpg", resource );  sender.send(message); 

if you want to use a Stream, then you can use

ByteArrayResource resource = new ByteArrayResource(IOUtils.toByteArray(inputStream))); 

instead of FileSystemResource

like image 30
Ralph Avatar answered Sep 21 '22 21:09

Ralph