Example usage for javax.mail Part getContentType

List of usage examples for javax.mail Part getContentType

Introduction

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

Prototype

public String getContentType() throws MessagingException;

Source Link

Document

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

Usage

From source file:uidmsgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/* ww w. jav  a  2 s  . c  o m*/

    /* Dump input stream
    InputStream is = new BufferedInputStream(p.getInputStream());
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
    */

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    Object o = p.getContent();
    if (o instanceof String) {
        System.out.println("This is a String");
        System.out.println("---------------------------");
        System.out.println((String) o);
    } else if (o instanceof Multipart) {
        System.out.println("This is a Multipart");
        System.out.println("---------------------------");
        Multipart mp = (Multipart) o;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
    } else if (o instanceof Message) {
        System.out.println("This is a Nested Message");
        System.out.println("---------------------------");
        dumpPart((Part) o);
    } else if (o instanceof InputStream) {
        System.out.println("This is just an input stream");
        System.out.println("---------------------------");
        InputStream is = (InputStream) o;
        int c;
        while ((c = is.read()) != -1)
            System.out.write(c);
    }
}

From source file:uidmsgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/*w  w  w .j  ava  2 s.c  o  m*/

    /*
     * Dump input stream InputStream is = new
     * BufferedInputStream(p.getInputStream()); int c; while ((c = is.read()) !=
     * -1) System.out.write(c);
     */

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    Object o = p.getContent();
    if (o instanceof String) {
        System.out.println("This is a String");
        System.out.println("---------------------------");
        System.out.println((String) o);
    } else if (o instanceof Multipart) {
        System.out.println("This is a Multipart");
        System.out.println("---------------------------");
        Multipart mp = (Multipart) o;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
    } else if (o instanceof Message) {
        System.out.println("This is a Nested Message");
        System.out.println("---------------------------");
        dumpPart((Part) o);
    } else if (o instanceof InputStream) {
        System.out.println("This is just an input stream");
        System.out.println("---------------------------");
        InputStream is = (InputStream) o;
        int c;
        while ((c = is.read()) != -1)
            System.out.write(c);
    }
}

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

/**
 * @param part/*from  www.  ja  v a  2  s.co  m*/
 * @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:mailbox.CreationViaEmail.java

private static Attachment saveAttachment(Part partToAttach, Resource container)
        throws MessagingException, IOException, NoSuchAlgorithmException {
    Attachment attach = new Attachment();
    String fileName = MimeUtility.decodeText(partToAttach.getFileName());
    attach.store(partToAttach.getInputStream(), fileName, container);
    if (!attach.mimeType.equalsIgnoreCase(partToAttach.getContentType())) {
        Logger.info("The email says the content type is '" + partToAttach.getContentType()
                + "' but Yobi determines it is '" + attach.mimeType + "'");
    }/*from ww  w  .  ja va 2  s. c  o  m*/

    return attach;
}

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

public static StringBuffer handlePart(Part messagePart, List<EmailAttachment> attachments,
        boolean ignoreAttachments) {
    StringBuffer body = new StringBuffer();
    try {/*from  w w w  . j a  v  a  2s.c om*/
        Object content = messagePart.getContent();
        // Retrieve content type
        String contentType = messagePart.getContentType();
        LOGGER.debug("Content type is " + contentType);
        // Check if this is a multipart message
        if (content instanceof Multipart) {
            LOGGER.debug("(Multipart-Email)");
            String s = handleMultipart(messagePart, attachments, ignoreAttachments);
            if (s != null) {
                body.append(s);
            }
        } else {
            // process regular message
            String s = handleSimplePart(messagePart, attachments, ignoreAttachments);
            if (s != null) {
                body.append(s);
            }
        }
    } catch (Exception ex) {
        LOGGER.error(ExceptionUtils.getStackTrace(ex));
    }
    return body;
}

From source file:com.stimulus.archiva.extraction.MessageExtraction.java

private static void dumpPart(Part p, Hashtable<String, Part> attachments, Hashtable<String, String> inlines,
        Hashtable<String, String> images, Hashtable<String, String> nonImages, ArrayList<String> mimeTypes,
        String subject) throws Exception {
    mimeTypes.add(p.getContentType());
    if (!p.isMimeType("multipart/*")) {

        String disp = p.getDisposition();
        String fname = p.getFileName();//  w ww.jav  a 2  s  .com
        if (fname != null) {
            try {
                fname = MimeUtility.decodeText(fname);
            } catch (Exception e) {
                logger.debug("cannot decode filename:" + e.getMessage());
            }
        }
        if ((disp != null && Compare.equalsIgnoreCase(disp, Part.ATTACHMENT)) || fname != null) {
            String filename = getFilename(subject, p);
            if (!filename.equalsIgnoreCase("winmail.dat")) {
                attachments.put(filename, p);
            }
            /*if (p.isMimeType("image/*")) {
               String str[] = p.getHeader("Content-ID");
               if (str != null) images.put(filename,str[0]);
               else images.put(filename, filename);
            }
            return;*/
        }
    }
    if (p.isMimeType("text/plain")) {
        String str = "";
        if (inlines.containsKey("text/plain"))
            str = (String) inlines.get("text/plain") + "\n\n-------------------------------\n";
        inlines.put("text/plain", str + getTextContent(p));
    } else if (p.isMimeType("text/html")) {
        inlines.put("text/html", getTextContent(p));
    } else if (p.isMimeType("text/xml")) {
        attachments.put(getFilename(subject, p), p);
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); i++)
            dumpPart(mp.getBodyPart(i), attachments, inlines, images, nonImages, mimeTypes, subject);
    } else if (p.isMimeType("message/rfc822")) {
        dumpPart((Part) p.getContent(), attachments, inlines, images, nonImages, mimeTypes, subject);
    } else if (p.isMimeType("application/ms-tnef")) {
        Part tnefpart = TNEFMime.convert(null, p, false);
        if (tnefpart != null) {
            dumpPart((Part) tnefpart, attachments, inlines, images, nonImages, mimeTypes, subject);
        }
    } else if (p.isMimeType("application/*")) {
        String filename = getFilename("application", p);
        attachments.put(filename, p);
        String str[] = p.getHeader("Content-ID");
        if (str != null)
            nonImages.put(filename, str[0]);
    } else if (p.isMimeType("image/*")) {
        String fileName = getFilename("image", p);
        attachments.put(fileName, p);
        String str[] = p.getHeader("Content-ID");
        if (str != null)
            images.put(fileName, str[0]);
        else
            images.put(fileName, fileName);
    } else {
        String contentType = p.getContentType();
        Object o = p.getContent();
        if (o instanceof String) {
            String str = "";
            if (inlines.containsKey("text/plain"))
                str = (String) inlines.get("text/plain") + "\n\n-------------------------------\n";
            inlines.put(contentType, str + (String) o);
        } else {
            String fileName = getFilenameFromContentType("attach", contentType);
            attachments.put(fileName, p);
        }
    }
}

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

/**
 * Processes part of a message/*from w  ww.  j av  a  2s  .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:com.aurel.track.util.emailHandling.MailReader.java

private static String hadleMultipartAlternative(Part part, List<EmailAttachment> attachments,
        boolean ignoreAttachments) throws IOException, MessagingException {
    LOGGER.debug("hadleMultipartAlternative");
    // prefer HTML text over plain text
    Multipart mp = (Multipart) part.getContent();
    String plainText = null;/*from  www.  ja v a2s.  c om*/
    String otherText = null;
    for (int i = 0; i < mp.getCount(); i++) {
        Part bp = mp.getBodyPart(i);
        if (bp.isMimeType("text/html")) {
            return getText(bp);
        } else if (bp.isMimeType("text/plain")) {
            plainText = getText(bp);
        } else {
            LOGGER.debug("Process alternative body part having mimeType:" + bp.getContentType());
            otherText = handlePart(bp, attachments, ignoreAttachments).toString();
        }
    }
    if (otherText != null) {
        return otherText;
    } else {
        return plainText;
    }
}

From source file:msgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/*from  w ww .  j  av a  2 s . co m*/

    /** Dump input stream .. 
            
    InputStream is = p.getInputStream();
    // If "is" is not already buffered, wrap a BufferedInputStream
    // around it.
    if (!(is instanceof BufferedInputStream))
        is = new BufferedInputStream(is);
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
            
    **/

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids
     * fetching the actual content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart) p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part) p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
            /*
             * If we actually want to see the data, and it's not a
             * MIME type we know, fetch it and check its Java type.
             */
            Object o = p.getContent();
            if (o instanceof String) {
                pr("This is a string");
                pr("---------------------------");
                System.out.println((String) o);
            } else if (o instanceof InputStream) {
                pr("This is just an input stream");
                pr("---------------------------");
                InputStream is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            } else {
                pr("This is an unknown type");
                pr("---------------------------");
                pr(o.toString());
            }
        } else {
            // just a separator
            pr("---------------------------");
        }
    }

    /*
     * If we're saving attachments, write out anything that
     * looks like an attachment into an appropriately named
     * file.  Don't overwrite existing files to prevent
     * mistakes.
     */
    if (saveAttachments && level != 0 && p instanceof MimeBodyPart && !p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // many mailers don't include a Content-Disposition
        if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (filename == null)
                filename = "Attachment" + attnum++;
            pr("Saving attachment to file " + filename);
            try {
                File f = new File(filename);
                if (f.exists())
                    // XXX - could try a series of names
                    throw new IOException("file exists");
                ((MimeBodyPart) p).saveFile(f);
            } catch (IOException ex) {
                pr("Failed to save attachment: " + ex);
            }
            pr("---------------------------");
        }
    }
}

From source file:MainClass.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);//from  w ww. j  a  va2  s  .c o  m

    /**
     * Dump input stream ..
     * 
     * InputStream is = p.getInputStream(); // If "is" is not already buffered,
     * wrap a BufferedInputStream // around it. if (!(is instanceof
     * BufferedInputStream)) is = new BufferedInputStream(is); int c; while ((c =
     * is.read()) != -1) System.out.write(c);
     * 
     */

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids fetching the actual
     * content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart) p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part) p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
            /*
             * If we actually want to see the data, and it's not a MIME type we
             * know, fetch it and check its Java type.
             */
            Object o = p.getContent();
            if (o instanceof String) {
                pr("This is a string");
                pr("---------------------------");
                System.out.println((String) o);
            } else if (o instanceof InputStream) {
                pr("This is just an input stream");
                pr("---------------------------");
                InputStream is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            } else {
                pr("This is an unknown type");
                pr("---------------------------");
                pr(o.toString());
            }
        } else {
            // just a separator
            pr("---------------------------");
        }
    }

    /*
     * If we're saving attachments, write out anything that looks like an
     * attachment into an appropriately named file. Don't overwrite existing
     * files to prevent mistakes.
     */
    if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // many mailers don't include a Content-Disposition
        if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (filename == null)
                filename = "Attachment" + attnum++;
            pr("Saving attachment to file " + filename);
            try {
                File f = new File(filename);
                if (f.exists())
                    // XXX - could try a series of names
                    throw new IOException("file exists");
                ((MimeBodyPart) p).saveFile(f);
            } catch (IOException ex) {
                pr("Failed to save attachment: " + ex);
            }
            pr("---------------------------");
        }
    }
}