title: Send email with javax.mail using an existing InputStream as attachment content
body: <p>Is it possible to send an email using <code>javax.mail</code> and using an “existing” <code>InputStream</code> for the email message attachment content?</p>
  
  <p>Currently I am building the email message as follows:</p>
  
  <pre><code>final MimeMessage message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
  message.setSubject("Subject line");
  
  final Multipart multipartContent = new MimeMultipart();
  
      final MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText("Message body");
      multipartContent.addBodyPart(textPart);
  
      final MimeBodyPart attachmentPart = new MimeBodyPart();
      final DataSource source = new InputStreamDataSource("text/plain", "test.txt", new ByteArrayInputStream("CONTENT INPUT STREAM".getBytes()));
      attachmentPart.setDataHandler(new DataHandler(source));
      attachmentPart.setFileName("text.txt");
      multipartContent.addBodyPart(attachmentPart);
  
  message.setContent(multipartContent);
  </code></pre>
  
  <p><code>InputStreamDataSource</code> is implemented as follows:</p>
  
  <pre><code>public class InputStreamDataSource implements DataSource
  {
      private final String contentType;
      private final String name;
      private final InputStream inputStream;
  
      public InputStreamDataSource(String contentType, String name, InputStream inputStream)
      {
          this.contentType = contentType;
          this.name = name;
          this.inputStream = inputStream;
      }
  
      public String getContentType()
      {
          return contentType;
      }
  
      public String getName()
      {
          return name;
      }
  
      public InputStream getInputStream() throws IOException
      {
          System.out.println("CALLED TWICE: InputStreamDataSource.getInputStream()");
          return new BufferedInputStream(inputStream);
          //return new ByteArrayInputStream("THIS 'NEW' INPUT STREAM WORKS BUT 'EXISTING' INPUT STREAM RESULTS IN ZERO-BYTE ATTACHMENT".getBytes());
      }
  
      public OutputStream getOutputStream() throws IOException
      {
          throw new UnsupportedOperationException("Not implemented");
      }
  }
  </code></pre>
  
  <p>The <code>DataSource</code> provides method <code>getInputStream()</code> to get the <code>InputStream</code> for the email message attachment content.</p>
  
  <p>If I return a "new" <code>InputStream</code> which does not depend on an "existing" <code>InputStream</code> then it works fine. But if I return an “existing” InputStream then the email message is delivered with a zero-byte attachment.</p>
  
  <p>Is it possible to send an email using <code>javax.mail</code>, and use an “existing” <code>InputStream</code> for the email message attachment content?</p>