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:msgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);// w w  w  . j  a  v a 2s.c om

    /** 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:org.apache.james.transport.mailets.StripAttachment.java

/**
 * Checks every part in this part (if it is a Multipart) for having a
 * filename that matches the pattern. If the name matches, the content of
 * the part is stored (using its name) in te given diretcory.
 * /*  w  w  w.j ava 2 s .c  om*/
 * Note: this method is recursive.
 * 
 * @param part
 *            The part to analyse.
 * @param mail
 * @return
 * @throws Exception
 */
private boolean analyseMultipartPartMessage(Part part, Mail mail) throws Exception {
    if (part.isMimeType("multipart/*")) {
        try {
            Multipart multipart = (Multipart) part.getContent();
            boolean atLeastOneRemoved = false;
            int numParts = multipart.getCount();
            for (int i = 0; i < numParts; i++) {
                Part p = multipart.getBodyPart(i);
                if (p.isMimeType("multipart/*")) {
                    atLeastOneRemoved |= analyseMultipartPartMessage(p, mail);
                } else {
                    boolean removed = checkMessageRemoved(p, mail);
                    if (removed) {
                        multipart.removeBodyPart(i);
                        atLeastOneRemoved = true;
                        i--;
                        numParts--;
                    }
                }
            }
            if (atLeastOneRemoved) {
                part.setContent(multipart);
                if (part instanceof Message) {
                    ((Message) part).saveChanges();
                }
            }
            return atLeastOneRemoved;
        } catch (Exception e) {
            log("Could not analyse part.", e);
        }
    }
    return false;
}

From source file:MainClass.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);//www  .j a va2 s.  com

    /**
     * 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("---------------------------");
        }
    }
}

From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java

private void parseMessagePart(Part messagePart) {
    try {//from w  w  w. jav  a 2 s .c  o  m
        if (messagePart.isMimeType(MIME_PLAIN_TEXT) || messagePart.isMimeType(MIME_HTML_TEXT)) {
            if (log.isDebugEnabled()) {
                log.debug("Text or HTML part was found. ContentType: " + messagePart.getContentType());
            }
            addBody(messagePart);
        } else if (messagePart.isMimeType(MIME_XML_TEXT)) {
            if (log.isDebugEnabled()) {
                log.debug("XML part was found.");
            }
            addAttachment(messagePart);
        } else if (messagePart.isMimeType(MIME_APPLICATION)) {
            if (log.isDebugEnabled()) {
                log.debug("Application part was found.");
            }
            addAttachment(messagePart);
        } else if (messagePart.isMimeType(MIME_IMAGE)) {
            if (log.isDebugEnabled()) {
                log.debug("Image part was found.");
            }
            addAttachment(messagePart);
        } else if (messagePart.isMimeType(MIME_MULTIPART)) {
            // if multipart, this method will be called recursively
            // for each of its parts
            Multipart mp = (Multipart) messagePart.getContent();
            int count = mp.getCount();

            if (log.isDebugEnabled()) {
                log.debug("MULTIPART with " + count + " part(s) found. Processin each part...");
            }
            for (int i = 0; i < count; i++) {
                BodyPart bp = mp.getBodyPart(i);
                if (bp.getContent() instanceof MimeMultipart) {
                    // It's multipart.  Recurse.
                    parseMessagePart(bp);
                } else {
                    // It's the body
                    addBody(bp);
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("MULTIPART processed.");
            }

        } else if (messagePart.isMimeType(MIME_RFC822)) {
            // if rfc822, call this method with its content as the part
            if (log.isDebugEnabled()) {
                log.debug("MIME_RFC822 part found. Processing inside part...");
            }

            parseMessagePart((Part) messagePart.getContent());

            if (log.isDebugEnabled()) {
                log.debug("MIME_RFC822 processed.");
            }

        } else {
            // if all else fails, put this in the attachments map.
            // Actually we don't know what it is.
            if (log.isDebugEnabled()) {
                log.debug("Unrecognized part was found. Put it into attachments.");
            }
            addAttachment(messagePart);
        }
    } catch (IOException e) {
        throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage());
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage());
    }
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

private void dumpPart(Part p, Element msg, Document doc) throws Exception {
    Element content = null;// w w  w .jav  a  2  s .  c  o m
    if (p.isMimeType("text/plain")) {
        content = doc.createElement("PlainMessage");
        Text body = doc.createTextNode((String) p.getContent());
        content.appendChild(body);
    } else if (p.isMimeType("text/html")) {
        content = doc.createElement("HTMLMessage");
        CDATASection body = doc.createCDATASection((String) p.getContent());
        content.appendChild(body);
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        content = doc.createElement("Multipart");
        for (int i = 0; i < count; i++) {
            dumpPart(mp.getBodyPart(i), content, doc);
        }
    } else if (p.isMimeType("message/rfc822")) {
        content = doc.createElement("NestedMessage");
        dumpPart((Part) p.getContent(), content, doc);
    } else {
        content = doc.createElement("EncodedContent");
        DataHandler dh = p.getDataHandler();
        OutputStream os = new ByteArrayOutputStream();
        Base64EncodingOutputStream b64os = new Base64EncodingOutputStream(os);
        dh.writeTo(b64os);
        b64os.flush();
        b64os.close();
        content.appendChild(doc.createTextNode(os.toString()));
    }
    msg.appendChild(content);
    String filename = p.getFileName();
    if (filename != null) {
        content.setAttribute("file-name", filename);
    }
    String ct = p.getContentType();
    if (ct != null) {
        content.setAttribute("content-type", ct);
    }
    String desc = p.getDescription();
    if (desc != null) {
        content.setAttribute("description", desc);
    }
}

From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java

/**
 * Return the primary text content of the message.
 */// ww w .  j  a v  a 2s.com
private String getText(Part p) throws MessagingException, IOException {
    if (p.isMimeType("text/*")) {
        return decodeMailBody(p);
    }

    if (p.isMimeType("multipart/alternative")) {
        // prefer html text over plain text
        Multipart mp = (Multipart) p.getContent();
        String text = null;
        for (int i = 0; i < mp.getCount(); i++) {
            Part bp = mp.getBodyPart(i);
            if (bp.isMimeType("text/plain")) {
                if (text == null) {
                    text = getText(bp);
                }
                continue;
            } else if (bp.isMimeType("text/html")) {
                String s = getText(bp);
                if (s != null) {
                    return s;
                }
            } else {
                return 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 null;
}

From source file:com.studiostorti.ZimbraFlowHandler.java

private String getText(Part mimeMessage) throws MessagingException, IOException {
    if (mimeMessage != null) {
        if (mimeMessage.isMimeType("text/plain")) {
            return (String) mimeMessage.getContent();
        }// w  ww. java  2s .co  m

        if (mimeMessage.isMimeType("multipart/alternative")) {
            Multipart multipart = (Multipart) mimeMessage.getContent();
            return getText(multipart.getBodyPart(0));
        } else if (mimeMessage.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) mimeMessage.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                String body = getText(multipart.getBodyPart(i));
                if (!body.equals(""))
                    return body;
            }
        }
    }

    return "";
}

From source file:com.glaf.mail.business.MailBean.java

/**
 * ??/*w  ww .  java2 s .c  o  m*/
 * 
 * @param part
 * @return
 * @throws MessagingException
 * @throws IOException
 */
public boolean isContainAttch(Part part) throws MessagingException, IOException {
    boolean flag = false;
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int count = multipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodypart = multipart.getBodyPart(i);
            String dispostion = bodypart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                flag = true;
            } else if (bodypart.isMimeType("multipart/*")) {
                flag = isContainAttch(bodypart);
            } else {
                String contentType = bodypart.getContentType();
                if (contentType.toLowerCase().indexOf("appliaction") != -1) {
                    flag = true;
                }
                if (contentType.toLowerCase().indexOf("name") != -1) {
                    flag = true;
                }
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        flag = isContainAttch((Part) part.getContent());
    }

    return flag;
}

From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java

private MessageBody createBodyFromPart(EmailMessage msg, Part part, boolean treatAsAttachement)
        throws MessagingException, IOException, ServiceLocalException {

    MessageBody mb = new MessageBody();
    if (part.isMimeType(TEXT_PLAIN)) {
        String s = (String) part.getContent();
        mb.setBodyType(BodyType.Text);
        mb.setText(s);/*from  ww  w  .  j  a va  2s.  c o  m*/
    } else if (part.isMimeType(TEXT_STAR)) {
        logger.debug("mime-type is '" + part.getContentType() + "' handling as " + TEXT_HTML);
        String s = (String) part.getContent();
        mb.setBodyType(BodyType.HTML);
        mb.setText(s);
    } else if (part.isMimeType(MULTIPART_ALTERNATIVE) && !treatAsAttachement) {
        logger.debug("mime-type is '" + part.getContentType() + "'");
        Multipart mp = (Multipart) part.getContent();
        String text = "";
        for (int i = 0; i < mp.getCount(); i++) {
            Part p = mp.getBodyPart(i);
            if (p.isMimeType(TEXT_HTML)) {
                text += p.getContent();
            }
        }
        mb.setText(text);
        mb.setBodyType(BodyType.HTML);
        if (!treatAsAttachement)
            createBodyFromPart(msg, part, true);
    } else if (part.isMimeType(MULTIPART_STAR) && !part.isMimeType(MULTIPART_ALTERNATIVE)) {
        logger.debug("mime-type is '" + part.getContentType() + "'");
        Multipart mp = (Multipart) part.getContent();
        int start = 0;
        if (!treatAsAttachement) {
            mb = createBodyFromPart(msg, mp.getBodyPart(start), false);
            start++;
        }
        for (int i = start; i < mp.getCount(); i++) {
            BodyPart lBodyPart = mp.getBodyPart(i);
            byte[] lContentBytes = bodyPart2ByteArray(lBodyPart);

            FileAttachment lNewAttachment;

            String lContentId = getFirstHeaderValue(lBodyPart, "Content-ID");
            if (lContentId != null) {
                lNewAttachment = msg.getAttachments().addFileAttachment(lContentId, lContentBytes);
                lNewAttachment.setContentId(lContentId);
                lNewAttachment.setIsInline(true);

                logger.debug("Attached {} bytes as content {}", lContentBytes.length, lContentId);
            } else {
                String fileName = lBodyPart.getFileName();
                fileName = (fileName == null ? "" + i : fileName);
                lNewAttachment = msg.getAttachments().addFileAttachment(fileName, lContentBytes);
                lNewAttachment.setIsInline(false);
                lNewAttachment.setContentType(lBodyPart.getContentType());

                logger.debug("Attached {} bytes as file {}", lContentBytes.length, fileName);
                logger.debug("content type is {} ", lBodyPart.getContentType());
            }
            lNewAttachment.setIsContactPhoto(false);
        }
    }
    return mb;
}

From source file:com.glaf.mail.business.MailBean.java

/**
 * ?//  ww  w.  j av a 2 s .  c o  m
 * 
 * @param part
 * @throws MessagingException
 * @throws IOException
 */
public void parseAttachment(Part part) throws MessagingException, IOException {
    String filename = "";
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart mpart = mp.getBodyPart(i);
            String dispostion = mpart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    logger.debug("filename=" + filename);
                    parseFileContent(filename, mpart.getInputStream());
                }
            } else if (mpart.isMimeType("multipart/*")) {
                parseAttachment(mpart);
            } else {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    parseFileContent(filename, mpart.getInputStream());
                    logger.debug("filename=" + filename);
                }
            }
        }

    } else if (part.isMimeType("message/rfc822")) {
        parseAttachment((Part) part.getContent());
    }
}