Example usage for javax.mail.internet MimePart getContentType

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

Introduction

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

Prototype

public String getContentType() throws MessagingException;

Source Link

Document

Returns the Content-Type of the content of this part.

Usage

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

public static MimeBodyPart makeContentBodyPart(MimePart sourcePart, HeaderMatcher matcher)
        throws MessagingException, IOException {
    MimeBodyPart newBodyPart = new MimeBodyPart();

    newBodyPart.setContent(sourcePart.getContent(), sourcePart.getContentType());

    HeaderUtils.copyHeaders(sourcePart, newBodyPart, matcher);

    return newBodyPart;
}

From source file:mailbox.CreationViaEmail.java

private static Content getContentWithAttachments(MimePart part) throws MessagingException, IOException {
    Content result = new Content();
    String rootId = new ContentType(part.getContentType()).getParameter("start");
    MimeMultipart mp = (MimeMultipart) part.getContent();
    for (int i = 0; i < mp.getCount(); i++) {
        MimePart p = (MimePart) mp.getBodyPart(i);
        if (isRootPart(p, i, rootId)) {
            result = result.merge(processPart(p, part));
        } else {//from   www. jav a 2s. c  o m
            result.attachments.add(p);
        }
    }
    return result;
}

From source file:mailbox.CreationViaEmail.java

private static Content getContent(MimePart part) throws IOException, MessagingException {
    Content result = new Content();
    result.body = (String) part.getContent();
    result.type = part.getContentType();
    return result;
}

From source file:com.zimbra.cs.service.mail.CreateContact.java

static String fetchItemPart(ZimbraSoapContext zsc, OperationContext octxt, Mailbox mbox, ItemId iid,
        String part, String[] acceptableMimeTypes, String charsetWanted) throws ServiceException {
    String text = null;/*from www . j a  va2  s. co m*/
    try {
        if (iid.isLocal()) {
            // fetch from local store
            if (!mbox.getAccountId().equals(iid.getAccountId())) {
                mbox = MailboxManager.getInstance().getMailboxByAccountId(iid.getAccountId());
            }
            Message msg = mbox.getMessageById(octxt, iid.getId());
            MimePart mp = Mime.getMimePart(msg.getMimeMessage(), part);
            String ctype = new ContentType(mp.getContentType()).getContentType();
            String fname = mp.getFileName();
            if (fname != null && (MimeConstants.CT_APPLICATION_OCTET_STREAM.equals(ctype)
                    || MimeConstants.CT_APPLICATION_TNEF.equals(ctype))) {
                String guess = MimeDetect.getMimeDetect().detect(fname);
                if (guess != null) {
                    ctype = guess;
                }
            }
            boolean typeAcceptable;
            if (acceptableMimeTypes != null) {
                typeAcceptable = false;
                for (String type : acceptableMimeTypes) {
                    if (type != null && type.equalsIgnoreCase(ctype)) {
                        typeAcceptable = true;
                        break;
                    }
                }
            } else {
                typeAcceptable = true;
            }
            if (!typeAcceptable)
                throw MailServiceException.INVALID_CONTENT_TYPE(ctype);
            text = Mime.getStringContent(mp, charsetWanted);
        } else {
            // fetch from remote store
            Map<String, String> params = new HashMap<String, String>();
            params.put(UserServlet.QP_PART, part);
            byte[] content = UserServlet.getRemoteContent(zsc.getAuthToken(), iid, params);
            text = new String(content, MimeConstants.P_CHARSET_UTF8);
        }
    } catch (IOException e) {
        throw ServiceException.FAILURE("error fetching message part: iid=" + iid + ", part=" + part, e);
    } catch (MessagingException e) {
        throw ServiceException.FAILURE("error fetching message part: iid=" + iid + ", part=" + part, e);
    }
    return text;
}

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   www. j  a v a2 s. com*/
 * 
 * @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.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 {// ww w .ja v  a2s .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 {/*from   w  w w.  jav a 2s .  c o  m*/
        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);
    }
}

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

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

    try {/*w  ww  .j a  v a  2  s. c om*/
        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:com.consol.citrus.mail.message.MailMessageConverter.java

/**
 * Process message part. Can be a text, binary or multipart instance.
 * @param part/* w w  w  .  ja v a 2  s  .  c o m*/
 * @return
 * @throws java.io.IOException
 */
protected BodyPart handlePart(MimePart part) throws IOException, MessagingException {
    String contentType = parseContentType(part.getContentType());

    if (part.isMimeType("multipart/*")) {
        return handleMultiPart((Multipart) part.getContent());
    } else if (part.isMimeType("text/*")) {
        return handleTextPart(part, contentType);
    } else if (part.isMimeType("image/*")) {
        return handleImageBinaryPart(part, contentType);
    } else if (part.isMimeType("application/*")) {
        return handleApplicationContentPart(part, contentType);
    } else {
        return handleBinaryPart(part, contentType);
    }
}

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

@Test
public void testFullContentType() throws Exception {
    String content = "From: user1@example.com\r\n" + "To: user2@example.com\r\n" + "Subject: test\r\n"
            + "Content-Type: text/plain;param=foo\r\n" + "Content-Transfer-Encoding: base64\r\n\r\n"
            + "R0a1231312ad124svsdsal=="; //obviously not a real file
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession(),
            new SharedByteArrayInputStream(content.getBytes()));

    MimePart part = Mime.getMimePart(mm, "1");
    Assert.assertEquals("text/plain;param=foo", part.getContentType());
    List<MPartInfo> parts = Mime.getParts(mm);
    Assert.assertNotNull(parts);//w ww  .j  a v  a  2  s  .c  om
    Assert.assertEquals(1, parts.size());
    MPartInfo info = parts.get(0);
    Assert.assertEquals("text/plain", info.getContentType());
    Assert.assertEquals("text/plain;param=foo", info.getFullContentType());
}