Example usage for javax.mail.internet MimePart getInputStream

List of usage examples for javax.mail.internet MimePart getInputStream

Introduction

In this page you can find the example usage for javax.mail.internet MimePart getInputStream.

Prototype

public InputStream getInputStream() throws IOException, MessagingException;

Source Link

Document

Return an input stream for this part's "content".

Usage

From source file:mitm.common.mail.MailUtils.java

/**
 * Converts any 8bit encoded parts to 7bit. Returns true if a part (or all parts) were converted from
 * 8bit to 7bit./*from  ww  w  .  j  a v a 2  s .  c  o m*/
 * 
 * @param part
 * @throws MessagingException
 */
public static boolean convertTo7Bit(MimePart part) throws MessagingException, IOException {
    boolean converted = false;

    if (part.isMimeType("multipart/*")) {
        Multipart parts = (Multipart) part.getContent();

        int count = parts.getCount();

        for (int i = 0; i < count; i++) {
            boolean partConverted = convertTo7Bit((MimePart) parts.getBodyPart(i));

            if (partConverted) {
                converted = true;
            }
        }
    } else if ("8bit".equalsIgnoreCase(part.getEncoding())) {
        String encoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";

        /*
         * We need to use a ByteArrayDataSource to make sure it will always be encoded
         */
        part.setDataHandler(
                new DataHandler(new ByteArrayDataSource(part.getInputStream(), part.getContentType())));

        part.setHeader("Content-Transfer-Encoding", encoding);
        part.addHeader("X-MIME-Autoconverted", "from 8bit to " + encoding + " by Djigzo");

        converted = true;
    }

    return converted;
}

From source file:com.consol.citrus.mail.message.MailMessageConverter.java

/**
 * Construct base64 body part from image data.
 * @param image//from   w  ww  .  ja  v  a2  s  .c  o m
 * @param contentType
 * @return
 * @throws IOException
 */
protected BodyPart handleImageBinaryPart(MimePart image, String contentType)
        throws IOException, MessagingException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    FileCopyUtils.copy(image.getInputStream(), bos);
    String base64 = Base64.encodeBase64String(bos.toByteArray());
    return new BodyPart(base64, contentType);
}

From source file:com.cubusmail.server.services.RetrieveImageServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from  ww w. j  ava 2 s  .  c o  m
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean isThumbnail = Boolean.valueOf(request.getParameter("thumbnail")).booleanValue();

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            if (isThumbnail) {
                List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
                int index = Integer.valueOf(attachmentIndex);

                MimePart retrievePart = attachmentList.get(index);

                ContentType contentType = new ContentType(retrievePart.getContentType());
                response.setContentType(contentType.getBaseType());

                BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
                OutputStream outputStream = response.getOutputStream();

                writeScaledImage(bufInputStream, outputStream);

                bufInputStream.close();
                outputStream.flush();
                outputStream.close();
            } else {
                Part imagePart = findImagePart(msg);
                if (imagePart != null) {
                    ContentType contentType = new ContentType(imagePart.getContentType());
                    response.setContentType(contentType.getBaseType());

                    BufferedInputStream bufInputStream = new BufferedInputStream(imagePart.getInputStream());
                    OutputStream outputStream = response.getOutputStream();

                    byte[] inBuf = new byte[1024];
                    int len = 0;
                    int total = 0;
                    while ((len = bufInputStream.read(inBuf)) > 0) {
                        outputStream.write(inBuf, 0, len);
                        total += len;
                    }

                    bufInputStream.close();
                    outputStream.flush();
                    outputStream.close();
                }
            }
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:mitm.common.mail.MailUtils.java

@SuppressWarnings("rawtypes")
public static void writeMessageRaw(MimePart part, OutputStream output) throws IOException, MessagingException {
    Enumeration lines = part.getAllHeaderLines();

    /* step through all header lines */
    while (lines.hasMoreElements()) {
        String header = (String) lines.nextElement();

        output.write(MiscStringUtils.toAsciiBytes(header));
        output.write(CRLF_BYTES);/*from w  w w  .  j a  va2s. c o  m*/
    }

    output.write(CRLF_BYTES);

    InputStream input;

    /*
     * 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 will try getInputStream.
     *
     * Only MimeMessage has getRawInputStream so we check whether the part 
     * is a MimeMessage
     */
    if (part instanceof MimeMessage) {
        try {
            input = ((MimeMessage) part).getRawInputStream();
        } catch (MessagingException e) {
            /*
             * Could be that we are using Javamail 1.3 which does not support 
             * getRawInputStream. Use the inputStream instead
             */
            input = part.getInputStream();
        }
    } else {
        input = part.getInputStream();
    }

    IOUtils.copy(input, output);
}

From source file:com.zimbra.cs.mime.Mime.java

/** Returns a String containing the text content of the MimePart.  If the
 *  part's specified charset is unknown, defaults first to the user's
 *  preferred charset and then to the to the system's default charset.
 *  Use this method instead of {@link Part#getContent()} to work around
 *  JavaMail's fascism about proper MIME format and failure to support
 *  RFC 2184. *///  ww w.ja  v a 2s.  c om
public static String getStringContent(MimePart textPart, String defaultCharset)
        throws IOException, MessagingException {
    repairTransferEncoding(textPart);
    return decodeText(textPart.getInputStream(), textPart.getContentType(), defaultCharset);
}

From source file:com.zimbra.cs.mime.Mime.java

/** Returns a <tt>Reader</tt> for the text content of the <tt>MimePart</tt>.  If the
 *  part's specified charset is unknown, defaults first to the user's
 *  preferred charset and then to the to the system's default charset.
 *  Use this method instead of {@link Part#getContent()} to work around
 *  JavaMail's fascism about proper MIME format and failure to support
 *  RFC 2184./*from   w w w  . j a v  a2 s  .  c  o m*/
 *
 *  @deprecated Use getTextReader() directly after calling repairTransferEncoding() as it's almost always
 *  necessary to drain and close the mimepart's input stream.
 *
 */

@Deprecated
public static Reader getContentAsReader(MimePart textPart, String defaultCharset)
        throws IOException, MessagingException {
    repairTransferEncoding(textPart);
    return getTextReader(textPart.getInputStream(), textPart.getContentType(), defaultCharset);
}

From source file:com.zimbra.cs.mime.Mime.java

/**
 * Returns the size of this <tt>MimePart</tt>'s content.  If the content
 * is encoded, returns the size of the decoded content.
 *///from   w ww  . ja  va2 s  . c  om
public static int getSize(MimePart part) throws MessagingException, IOException {
    int size = part.getSize();
    if (size > 0) {
        if ("base64".equalsIgnoreCase(part.getEncoding())) {
            // MimePart.getSize() returns the encoded size.
            int lines = (size + 77) / 78;
            size = (int) (0.75 * (size - 2 * lines));
        }
    } else {
        size = (int) ByteUtil.getDataLength(part.getInputStream());
    }
    return size;
}

From source file:com.zimbra.cs.mime.Mime.java

/** Returns the MimeMessage object encapsulating a MIME part with
 *  content-type "message/rfc822".  Use this method instead of
 *  {@link Part#getContent()} to work around JavaMail's fascism about
 *  proper MIME format and failure to support RFC 2184. */
public static MimeMessage getMessageContent(MimePart message822Part) throws IOException, MessagingException {
    String ctype = getContentType(message822Part);
    if (MimeConstants.CT_MESSAGE_RFC822.equals(ctype)) {
        // JavaMail will only return a correct MimeMessage if the Content-Type header was set correctly
        Object content = message822Part.getContent();
        if (content instanceof MimeMessage)
            return (MimeMessage) content;
    }/*  www  . ja  va 2 s.  c  om*/

    InputStream is = null;
    try {
        // handle unparsed content due to multipart/digest or miscapitalization of content-type value
        return new FixedMimeMessage(JMSession.getSession(), is = message822Part.getInputStream());
    } catch (Exception e) {
    } finally {
        ByteUtil.closeStream(is);
    }
    return null;
}

From source file:com.cubusmail.gwtui.server.services.RetrieveAttachmentServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(request.getSession().getServletContext());

    try {//from ww w .j av a2  s  . c om
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean view = "1".equals(request.getParameter("view"));

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
            int index = Integer.valueOf(attachmentIndex);

            MimePart retrievePart = attachmentList.get(index);

            ContentType contentType = new ContentType(retrievePart.getContentType());

            String fileName = retrievePart.getFileName();
            if (StringUtils.isEmpty(fileName)) {
                fileName = context.getMessage("message.unknown.attachment", null,
                        SessionManager.get().getLocale());
            }
            StringBuffer contentDisposition = new StringBuffer();
            if (!view) {
                contentDisposition.append("attachment; filename=\"");
                contentDisposition.append(fileName).append("\"");
            }

            response.setHeader("cache-control", "no-store");
            response.setHeader("pragma", "no-cache");
            response.setIntHeader("max-age", 0);
            response.setIntHeader("expires", 0);

            if (!StringUtils.isEmpty(contentDisposition.toString())) {
                response.setHeader("Content-disposition", contentDisposition.toString());
            }
            response.setContentType(contentType.getBaseType());
            // response.setContentLength(
            // MessageUtils.calculateSizeFromPart( retrievePart ) );

            BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
                outputStream.write(inBuf, 0, len);
                total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();

        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:com.cubusmail.server.services.RetrieveAttachmentServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(request.getSession().getServletContext());

    try {//ww w.j a v a2 s  .  com
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean view = "1".equals(request.getParameter("view"));

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
            int index = Integer.valueOf(attachmentIndex);

            MimePart retrievePart = attachmentList.get(index);

            ContentType contentType = new ContentType(retrievePart.getContentType());

            String fileName = retrievePart.getFileName();
            if (StringUtils.isEmpty(fileName)) {
                fileName = context.getMessage("message.unknown.attachment", null,
                        SessionManager.get().getLocale());
            }
            StringBuffer contentDisposition = new StringBuffer();
            if (!view) {
                contentDisposition.append("attachment; filename=\"");
                contentDisposition.append(fileName).append("\"");
            }

            response.setHeader("cache-control", "no-store");
            response.setHeader("pragma", "no-cache");
            response.setIntHeader("max-age", 0);
            response.setIntHeader("expires", 0);

            if (!StringUtils.isEmpty(contentDisposition.toString())) {
                response.setHeader("Content-disposition", contentDisposition.toString());
            }
            response.setContentType(contentType.getBaseType());
            // response.setContentLength(
            // MessageUtils.calculateSizeFromPart( retrievePart ) );

            BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
                outputStream.write(inBuf, 0, len);
                total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();

        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}