Example usage for javax.mail Part isMimeType

List of usage examples for javax.mail Part isMimeType

Introduction

In this page you can find the example usage for javax.mail Part isMimeType.

Prototype

public boolean isMimeType(String mimeType) throws MessagingException;

Source Link

Document

Is this Part of the specified MIME type?

Usage

From source file:de.saly.elasticsearch.support.IndexableMailMessage.java

private static String getText(final Part p, int depth) throws MessagingException, IOException {

    if (depth >= 100) {
        throw new IOException("Endless recursion detected ");
    }//from  w  w  w. j  a  v  a  2  s . c o m

    // TODO fix encoding for buggy encoding headers

    if (p.isMimeType("text/*")) {

        Object content = null;
        try {
            content = p.getContent();
        } catch (final Exception e) {
            logger.error("Unable to index the content of a message due to {}", e.toString());
            return null;
        }

        if (content instanceof String) {
            final String s = (String) p.getContent();
            return s;

        }

        if (content instanceof InputStream) {

            final InputStream in = (InputStream) content;
            // TODO guess encoding with
            // http://code.google.com/p/juniversalchardet/
            final String s = IOUtils.toString(in, "UTF-8");
            IOUtils.closeQuietly(in);
            return s;

        }

        throw new MessagingException("Unknown content class representation: " + content.getClass());

    }

    if (p.isMimeType("multipart/alternative")) {
        // prefer plain text over html text
        final Multipart mp = (Multipart) p.getContent();
        String text = null;
        for (int i = 0; i < mp.getCount(); i++) {
            final Part bp = mp.getBodyPart(i);
            if (bp.isMimeType("text/html")) {
                if (text == null) {
                    text = getText(bp, ++depth);
                }
                continue;
            } else if (bp.isMimeType("text/plain")) {
                final String s = getText(bp, ++depth);
                if (s != null) {
                    return s;
                }
            } else {
                return getText(bp, ++depth);
            }
        }
        return text;
    } else if (p.isMimeType("multipart/*")) {
        final Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            final String s = getText(mp.getBodyPart(i), ++depth);
            if (s != null) {
                return s;
            }
        }
    }

    return null;
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

private static String handleInline(Part part, List attachments, boolean ignoreAttachments)
        throws MessagingException, IOException {
    String fileName = part.getFileName();
    if (fileName != null) {
        // this is an attachment
        if (ignoreAttachments == false) {
            handleAttachment(part, attachments);
        }//  w  w  w  .j  a  v  a2 s .  c  o m
        return null;
    }
    // inline content
    if (part.isMimeType("text/*")) {
        return getText(part);
    } else {
        // binary inline content and no fileNameprovide
        // treat as attachemnt with unknow file name
        if (ignoreAttachments == false) {
            handleAttachment(part, attachments);
        }
        return null;
    }
}

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

private static String getText(final Part p, int depth, final boolean preferHtmlContent)
        throws MessagingException, IOException {

    if (depth >= 100) {
        throw new IOException("Endless recursion detected ");
    }/*from ww w .j av  a2 s .  c o  m*/

    // TODO fix encoding for buggy encoding headers

    if (p.isMimeType("text/*")) {

        Object content = null;
        try {
            content = p.getContent();
        } catch (final Exception e) {
            logger.error("Unable to index the content of a message due to {}", e.toString());
            return null;
        }

        if (content instanceof String) {
            final String s = (String) p.getContent();
            return s;

        }

        if (content instanceof InputStream) {

            final InputStream in = (InputStream) content;
            // TODO guess encoding with
            // http://code.google.com/p/juniversalchardet/
            final String s = IOUtils.toString(in, "UTF-8");
            IOUtils.closeQuietly(in);
            return s;

        }

        throw new MessagingException("Unknown content class representation: " + content.getClass());

    }

    if (p.isMimeType("multipart/alternative")) {
        // prefer plain text over html text
        final Multipart mp = (Multipart) p.getContent();
        String text = null;
        for (int i = 0; i < mp.getCount(); i++) {
            final Part bp = mp.getBodyPart(i);
            if (bp.isMimeType("text/html")) {
                if (text == null) {
                    text = getText(bp, ++depth, preferHtmlContent);
                }
                if (preferHtmlContent) {
                    return text;
                } else {
                    continue;
                }
            } else if (bp.isMimeType("text/plain")) {
                final String s = getText(bp, ++depth, preferHtmlContent);
                if (s != null && !preferHtmlContent) {
                    return s;
                } else {
                    continue;
                }
            } else {
                return getText(bp, ++depth, preferHtmlContent);
            }
        }
        return text;
    } else if (p.isMimeType("multipart/*")) {
        final Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            final String s = getText(mp.getBodyPart(i), ++depth, preferHtmlContent);
            if (s != null) {
                return s;
            }
        }
    }

    return null;
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

/**
 * Processes part of a message/*from   ww  w .j  a v  a  2 s  .  c  o m*/
 */
private static String handleSimplePart(Part part, List<EmailAttachment> attachments, boolean ignoreAttachments)
        throws MessagingException, IOException {
    // Check for content disposition and content type
    String disposition = part.getDisposition();
    String contentType = part.getContentType();
    LOGGER.debug("disposition=" + disposition);
    LOGGER.debug("Body type is: " + contentType);

    // tread if the part is a message
    boolean inlineMessage = part.isMimeType("message/rfc822");
    if (inlineMessage) {
        LOGGER.debug("Inner message:" + part.getFileName());
        Message subMessage = (Message) part.getContent();
        StringBuffer s = handlePart(subMessage, attachments, ignoreAttachments);
        System.out.println();
        return s.toString();
    }
    if (disposition == null) {
        if ("image/BMP".equals(contentType)) {
            // BMP image add as attachment
            if (ignoreAttachments == false) {
                try {
                    attachments.add(createEmailAttachment(part, "image.bmp"));
                } catch (Exception e) {
                    // just ignore
                }
            }
            return null;
        } else if (part.isMimeType("text/*")) {
            return getText(part);
        } else {
            if (ignoreAttachments == false) {
                handleAttachment(part, attachments);
            }
            return null;
        }
    }
    if (disposition.equalsIgnoreCase(Part.INLINE)) {
        return handleInline(part, attachments, ignoreAttachments);
    }
    if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
        if (ignoreAttachments == false) {
            handleAttachment(part, attachments);
        }
        return null;
    }
    LOGGER.debug("Unknown disposition:" + disposition + "Threat as attachment");
    if (ignoreAttachments == false) {
        handleAttachment(part, attachments);
    }
    return null;
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static List<AttachmentInfo> saveAttachmentToWeedFs(Part message, List<AttachmentInfo> attachments,
        EmailRiverConfig config)// ww w .j av a 2  s . c om
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (attachments == null) {
        attachments = new ArrayList<AttachmentInfo>();
    }
    boolean hasAttachment = false;
    try {
        hasAttachment = isContainAttachment(message);
    } catch (MessagingException e) {
        logger.error("save attachment", e);
    } catch (IOException e) {
        logger.error("save attachment", e);
    }
    if (hasAttachment) {

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

            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {

                BodyPart bodyPart = multipart.getBodyPart(i);

                String disp = bodyPart.getDisposition();
                if (disp != null
                        && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();

                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int len = -1;
                    while ((len = bis.read()) != -1) {
                        bos.write(len);
                    }
                    bos.close();
                    bis.close();

                    byte[] data = bos.toByteArray();
                    String fileId = uploadFileToWeedfs(data, config);
                    if (fileId != null) {
                        AttachmentInfo info = new AttachmentInfo();
                        info.fileId = fileId;
                        info.fileName = decodeText(bodyPart.getFileName());
                        info.fileSize = data.length;
                        attachments.add(info);
                    }

                } else if (bodyPart.isMimeType("multipart/*")) {

                    attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));

                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));
                    }
                }
            }
        } else if (message.isMimeType("message/rfc822")) {

            attachments.addAll(saveAttachmentToWeedFs(message, attachments, config));

        }

    }
    return attachments;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Get text from message/*from   w ww.j av a  2  s .  com*/
 */
private static String getText(Part p) throws MessagingException, IOException {
    if (p.isMimeType("text/*")) {
        Object obj = p.getContent();
        String str = NO_BODY;

        if (obj instanceof InputStream) {
            InputStream is = (InputStream) obj;
            StringWriter writer = new StringWriter();
            IOUtils.copy(is, writer, "UTF-8");
            str = writer.toString();
        } else {
            str = (String) obj;
        }

        if (p.isMimeType("text/html")) {
            return "H" + str;
        } else if (p.isMimeType("text/plain")) {
            return "T" + str;
        } else {
            // Otherwise let's set as text/plain
            return "T" + str;
        }
    } else if (p.isMimeType("multipart/alternative")) {
        // prefer html over plain text
        Multipart mp = (Multipart) p.getContent();
        String text = "T" + NO_BODY;
        // log.info("Mime Parts: {}", mp.getCount());

        for (int i = 0; i < mp.getCount(); i++) {
            Part bp = mp.getBodyPart(i);

            if (bp.isMimeType("text/plain")) {
                text = getText(bp);
            } else if (bp.isMimeType("text/html")) {
                text = getText(bp);
                break;
            } else {
                text = getText(bp);
            }
        }

        return text;
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();

        for (int i = 0; i < mp.getCount(); i++) {
            String s = getText(mp.getBodyPart(i));

            if (s != null)
                return s;
        }
    }

    return "T" + NO_BODY;
}

From source file:org.silverpeas.core.mail.extractor.EMLExtractor.java

private String getBody(Multipart multipart) throws MessagingException, IOException {
    int partsNumber = multipart.getCount();
    String body = "";
    for (int i = 0; i < partsNumber; i++) {
        Part part = multipart.getBodyPart(i);
        if (part.isMimeType(MimeTypes.HTML_MIME_TYPE)) {
            // if present, return always HTML part
            return (String) part.getContent();
        } else if (part.isMimeType(MimeTypes.PLAIN_TEXT_MIME_TYPE)) {
            body = WebEncodeHelper.javaStringToHtmlParagraphe((String) part.getContent());
        } else if (part.getContent() instanceof Multipart) {
            return getBody((Multipart) part.getContent());
        }// www.  j  av  a  2 s .c om
    }
    return body;
}

From source file:org.silverpeas.util.mail.EMLExtractor.java

private String getBody(Multipart multipart) throws MessagingException, IOException {
    int partsNumber = multipart.getCount();
    String body = "";
    for (int i = 0; i < partsNumber; i++) {
        Part part = multipart.getBodyPart(i);
        if (part.isMimeType(MimeTypes.HTML_MIME_TYPE)) {
            // if present, return always HTML part
            return (String) part.getContent();
        } else if (part.isMimeType(MimeTypes.PLAIN_TEXT_MIME_TYPE)) {
            body = EncodeHelper.javaStringToHtmlParagraphe((String) part.getContent());
        } else if (part.getContent() instanceof Multipart) {
            return getBody((Multipart) part.getContent());
        }//from   w  w  w  .java2 s.c o m
    }
    return body;
}

From source file:com.cubusmail.mail.text.MessageTextUtil.java

/**
 * @param part/*from w  ww.  jav  a 2 s. com*/
 * @param messageHandler
 * @param loadImages
 * @param reply
 * @throws MessagingException
 * @throws IOException
 */
public static void messageTextFromPart(Part part, MessageHandler messageHandler, boolean loadImages,
        MessageTextMode mode, Preferences preferences, int level) throws MessagingException, IOException {

    log.debug("Content type of part: " + part.getContentType());

    if (mode == MessageTextMode.DISPLAY || mode == MessageTextMode.DRAFT) {
        if (MessageUtils.isImagepart(part)) {
            messageHandler.setMessageImageHtml(createImageMessageText(messageHandler.getId()));
        } else if (!preferences.isShowHtml() && !StringUtils.isEmpty(messageHandler.getMessageTextPlain())) {
            return;
        } else if (preferences.isShowHtml() && !StringUtils.isEmpty(messageHandler.getMessageTextHtml())) {
            return;
        } else if (part.isMimeType("text/plain")) {
            String text = readPart(part);
            if (!StringUtils.isBlank(text)) {
                messageHandler.setMessageTextPlain(formatPlainText(text, mode));
            }
        } else if (part.isMimeType("text/html")) {
            if (preferences.isShowHtml()) {
                String text = readPart(part);
                boolean[] hasImages = new boolean[] { false };
                if (!StringUtils.isBlank(convertHtml2PlainText(text))) {
                    text = formatHTMLText(text, loadImages, hasImages);
                    messageHandler.setMessageTextHtml(text);
                    messageHandler.setHtmlMessage(true);
                    messageHandler.setHasImages(hasImages[0]);
                }
            } else {
                // only if there is no plain text part found
                if (StringUtils.isEmpty(messageHandler.getMessageTextPlain())) {
                    String text = readPart(part);
                    text = convertHtml2PlainText(text);
                    if (!StringUtils.isBlank(text)) {
                        text = formatPlainText(text, mode);
                        messageHandler.setMessageTextPlain(text);
                    }
                }
            }
        } else if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                Part subPart = mp.getBodyPart(i);
                messageTextFromPart(subPart, messageHandler, loadImages, mode, preferences, level++);
            }
        }
    } else if (mode == MessageTextMode.REPLY) {
        if (!preferences.isCreateHtmlMsgs() && !StringUtils.isEmpty(messageHandler.getMessageTextPlain())) {
            return;
        } else if (preferences.isCreateHtmlMsgs()
                && !StringUtils.isEmpty(messageHandler.getMessageTextHtml())) {
            return;
        } else if (part.isMimeType("text/plain")) {
            String text = readPart(part);
            text = quotePlainText(text);
            if (preferences.isCreateHtmlMsgs()) {
                text = convertPlainText2Html(text, mode);
                messageHandler.setMessageTextHtml(text);
                messageHandler.setHtmlMessage(true);
            } else {
                messageHandler.setMessageTextPlain(text);
            }
        } else if (part.isMimeType("text/html") && StringUtils.isEmpty(messageHandler.getMessageTextPlain())) {
            String text = readPart(part);
            text = convertHtml2PlainText(text);
            text = quotePlainText(text);
            if (preferences.isCreateHtmlMsgs()) {
                text = convertPlainText2Html(text, mode);
                messageHandler.setMessageTextHtml(text);
                messageHandler.setHtmlMessage(true);
            } else {
                messageHandler.setMessageTextPlain(text);
            }
        } else if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                Part subPart = mp.getBodyPart(i);
                messageTextFromPart(subPart, messageHandler, loadImages, mode, preferences, level++);
            }
        }
    }
}

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

/**
 * @param parent/*from  w w w. ja v a 2s  .  com*/
 * @return
 */
private Part findImagePart(Part parent) {

    try {
        if (MessageUtils.isImagepart(parent)) {
            return parent;
        } else if (parent.isMimeType("multipart/*")) {
            Multipart mp;
            mp = (Multipart) parent.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                Part subPart = findImagePart(mp.getBodyPart(i));
                if (subPart != null) {
                    return subPart;
                }
            }
        }
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return null;
}