List of usage examples for javax.mail BodyPart writeTo
public void writeTo(OutputStream os) throws IOException, MessagingException;
From source file:mitm.common.security.smime.SMIMEUtils.java
public static void writeBodyPart(BodyPart bodyPart, OutputStream output, String defaultContentTransferEncoding) throws IOException, MessagingException { if (bodyPart instanceof MimeBodyPart) { MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart; String[] contentTransferEncodings = bodyPart.getHeader("Content-Transfer-Encoding"); String contentTransferEncoding = defaultContentTransferEncoding; if (contentTransferEncodings != null && contentTransferEncodings.length > 0) { contentTransferEncoding = contentTransferEncodings[0]; }/*w w w . j a va 2 s. co m*/ /* * First try the raw input stream. * If message is created from a stream Javamail will return the raw stream. If * the message is created from 'scratch' getRawInputStream throws a * MessagingException. We will therefore first try the raw version and if * that fails we fallback on writeTo. */ try { InputStream input = mimeBodyPart.getRawInputStream(); Enumeration<?> lines = mimeBodyPart.getAllHeaderLines(); /* step through all header lines */ while (lines.hasMoreElements()) { String header = (String) lines.nextElement(); output.write(MiscStringUtils.toAsciiBytes(header)); output.write(MailUtils.CRLF_BYTES); } output.write(MailUtils.CRLF_BYTES); if (!contentTransferEncoding.equalsIgnoreCase("binary")) { output = new CRLFOutputStream(output); } IOUtils.copy(input, output); output.flush(); } catch (MessagingException e) { /* * Fallback to writeTo */ if (!contentTransferEncoding.equalsIgnoreCase("binary")) { output = new CRLFOutputStream(output); } bodyPart.writeTo(output); output.flush(); } } else { if (!defaultContentTransferEncoding.equalsIgnoreCase("binary")) { output = new CRLFOutputStream(output); } bodyPart.writeTo(output); output.flush(); } }