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?
Yes, this is possible. The answer employing ByteArrayDataSource does not provide a satisfactory solution for large attachments because it requires that the entire content reside in memory at once. A better solution is to use a DataHandler that is fed by a PipedInputStream, which in turn is written to by a PipedOutputStream. Of course, this requires a second Thread. The code below demonstrates this:
You can run this code with the following properties (edited as appropriate) defined on the command line:
The example code sends an email with a text/plain cover letter with us-ascii encoding and a text/plain attachment with utf-8 encoding with a base64 transfer encoding. It also uses STARTTLS (encrypted transfer) if the MX supports it.
Try using ByteArrayDataSource, like this