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.
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);
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)));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With