Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add attachments to email in Java using OutputStream?

I've seen the code for javax.mail library where you add attachments to the email doing this:

MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("C:/text.txt");
attachmentPart.setDataHandler(new DataHandler(fds));
attachmentPart.setFileName("text.txt");
multipart.addBodyPart(attachmentPart);

But this requires that the file reside somewhere on this disk.

I would like to grab an OutputStream right from the email library and stream file contents into it directly from another place where I write to that OutputStream.

Is this possible?

like image 936
Reimius Avatar asked Mar 29 '13 19:03

Reimius


People also ask

How can I send multiple attachments by email in Java?

setText(body); multipart. addBodyPart(msgBodyPart); msgBodyPart = new MimeBodyPart(); //attach file DataSource source = new FileDataSource(attachFile); messageBodyPart. setDataHandler(new DataHandler(source)); messageBodyPart. setFileName(attachFile); multipart.


1 Answers

Try using ByteArrayDataSource, like this

ByteArrayOutputStream baos = //Read the output stream
DataSource aAttachment = new  ByteArrayDataSource(baos.toByteArray(),"application/octet-stream");
MimeBodyPart attachmentPart = new MimeBodyPart();

attachmentPart.setDataHandler(new DataHandler(aAttachment));
like image 63
NullPointerException Avatar answered Nov 15 '22 16:11

NullPointerException