Example usage for javax.mail Part getDescription

List of usage examples for javax.mail Part getDescription

Introduction

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

Prototype

public String getDescription() throws MessagingException;

Source Link

Document

Return a description String for this part.

Usage

From source file:org.zilverline.core.IMAPCollection.java

/**
 * Index a part./*from   w  w w  .  ja v a  2  s. c o m*/
 */
private void indexPart(final Document doc, final Part p) throws MessagingException, IOException {
    int size = p.getSize();
    String ct = p.getContentType();
    String cd = p.getDescription();
    log.debug("IndexContent, type: " + ct + ", description: " + cd);
    Object content = null;

    if (ct != null) {
        doc.add(Field.Keyword(F_CT, ct));
    }
    doc.add(Field.Keyword("type", "MAIL"));

    if (cd != null) {
        doc.add(Field.Keyword(F_CD, cd));
    }

    if (ct != null && ct.toLowerCase().startsWith("image/")) {
        // no point for now but maybe in the future we see if any forms such as jpegs have some strings
        return;
    }

    try {
        // get content object, indirectly calls into JAF which decodes based on MIME type and char
        content = p.getContent();
    } catch (IOException ioe) {
        log.warn("OUCH decoding attachment, p=" + p, ioe);
        doc.add(Field.Text(F_CONTENTS, new InputStreamReader(p.getInputStream())));
        return;
    }

    if (content instanceof MimeMultipart) {
        int n = ((MimeMultipart) content).getCount();
        for (int i = 0; i < n; i++) {
            BodyPart bp = ((MimeMultipart) content).getBodyPart(i);
            // same thing ends up happening regardless, if/else left it to show structure
            indexPart(doc, bp);
        }
    } else if (content instanceof MimePart) {
        indexPart(doc, (MimePart) content);
    } else if (content instanceof Part) {
        indexPart(doc, (Part) content);
    } else if (content instanceof String) {
        indexString(doc, (String) content, ct);
    } else if (content instanceof InputStream) {
        indexStream(doc, (InputStream) content, ct);
    } else {
        log.error("***** Strange content: " + content + "/" + content.getClass() + " ct=" + ct + " cd=" + cd);
    }
}

From source file:mitm.common.pdf.MessagePDFBuilder.java

private String getFilename(Part part, String defaultIfNull) {
    String filename = null;/*from w ww  .ja  v  a 2s .c o  m*/

    filename = HeaderUtils.decodeTextQuietly(MimeUtils.getFilenameQuietly(part));

    if (filename == null) {
        try {
            filename = part.getDescription();
        } catch (MessagingException e) {
        }

        if (filename == null) {
            filename = defaultIfNull;
        }
    }

    return filename;
}

From source file:dtw.webmail.model.JwmaMessagePartImpl.java

/**
 * Creates a <tt>JwmaMessagePartImpl</tt> instance from a given
 * <tt>javax.mail.Part</tt> instance.
 *
 * @param part a <tt>javax.mail.Part</tt> instance.
 * @param number the number of the part as <tt>int</tt>.
 *
 * @return the newly created instance.//  w  ww .  ja va  2 s.co m
 * @throws JwmaException if it fails to create the new instance.
 */
public static JwmaMessagePartImpl createJwmaMessagePartImpl(Part part, int number) throws JwmaException {
    JwmaMessagePartImpl partinfo = new JwmaMessagePartImpl(part, number);

    //content type
    try {
        partinfo.setContentType(part.getContentType());

        //size
        int size = part.getSize();
        //JwmaKernel.getReference().debugLog().write("Part size="+size);
        String fileName = part.getFileName();
        //correct size of encoded parts
        String[] encoding = part.getHeader("Content-Transfer-Encoding");
        if (fileName != null && encoding != null && encoding.length > 0
                && (encoding[0].equalsIgnoreCase("base64") || encoding[0].equalsIgnoreCase("uuencode"))) {
            if ((fileName.startsWith("=?GB2312?B?") && fileName.endsWith("?="))) {
                byte[] decoded = Base64.decodeBase64(fileName.substring(11, fileName.indexOf("?=")).getBytes());
                fileName = new String(decoded, "GB2312");
                /*fileName = CipherUtils.decrypt(fileName);
                System.out.println("fileName----"+fileName);*/
                //fileName = getFromBASE64(fileName.substring(11,fileName.indexOf("?=")));  
            } else if ((fileName.startsWith("=?UTF-8?") || fileName.startsWith("=?UTF8?"))
                    && fileName.endsWith("?=")) {
                fileName = MimeUtility.decodeText(fileName);
            }
            //an encoded file is about 35% smaller in reality,
            //so correct the size
            size = (int) (size * 0.65);
        }

        partinfo.setSize(size);
        //description
        partinfo.setDescription(part.getDescription());

        //filename
        partinfo.setName(fileName);

        //textcontent
        if (partinfo.isMimeType("text/*")) {
            Object content = part.getContent();
            if (content instanceof String) {
                partinfo.setTextContent((String) content);
            } else if (content instanceof InputStream) {
                InputStream in = (InputStream) content;
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int amount = 0;
                while ((amount = in.read(buffer)) >= 0) {
                    bout.write(buffer, 0, amount);
                }
                partinfo.setTextContent(new String(bout.toString()));
            }
        }
    } catch (Exception mex) {
        throw new JwmaException("jwma.messagepart.failedcreation", true).setException(mex);
    }
    return partinfo;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Get the name of a part. The part is interogated for a valid name from
 * the provided file name or description.
 *
 * @param part The part to interogate/*from   ww  w  . j a v  a 2 s .c  o  m*/
 *
 * @return String containing the name of the part
 *
 * @exception MessagingException if contents of the part are invalid
 *
 * @see javax.mail.Part
 */
public static String getPartName(Part part) throws MessagingException {
    String xdescription = MessageUtilities.getFileName(part);

    if ((xdescription == null) || (xdescription.length() < 1)) {
        xdescription = part.getDescription();
    }

    if (((xdescription == null) || (xdescription.length() < 1)) && part instanceof MimePart) {
        xdescription = ((MimePart) part).getContentID();
    }

    if ((xdescription == null) || (xdescription.length() < 1)) {
        xdescription = "Message Text";
    }

    return xdescription;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*from ww  w  .  jav  a  2s.co  m*/
 *
 * @param multipart DOCUMENT ME!
 * @param part DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, Part part, String charset) throws MessagingException {
    MimeBodyPart xbody = new MimeBodyPart();
    PartDataSource xds = new PartDataSource(part);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    int xid = multipart.getCount() + 1;
    String xtext;

    // UNDONE
    //xbody.setContentLanguage( String ); // this could be language from Locale
    //xbody.setContentMD5( String md5 ); // don't know about this yet
    xtext = part.getDescription();

    if (xtext == null) {
        xtext = "Part Attachment: " + xid;
    }

    xbody.setDescription(xtext, charset);

    xtext = getContentDisposition(part).getType();
    xbody.setDisposition(xtext);

    xtext = MessageUtilities.getFileName(part);

    if ((xtext == null) || (xtext.length() < 1)) {
        xtext = "PART" + xid;
    }

    MessageUtilities.setFileName(xbody, xtext, charset);

    multipart.addBodyPart(xbody);
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Get a textual description of a part.//from w ww  .  j  a  va 2s.  c o m
 *
 * @param part The part to interogate
 * @param buf a string buffer for the description
 * @param prefix a prefix for each line of the description
 * @param recurse boolean specifying wether to recurse through sub-parts or
 *        not
 *
 * @return StringBuffer containing the description of the part
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static StringBuffer getPartDescription(Part part, StringBuffer buf, String prefix, boolean recurse)
        throws MessagingException {
    if (buf == null) {
        return buf;
    }

    ContentType xctype = MessageUtilities.getContentType(part);

    String xvalue = xctype.toString();
    buf.append(prefix);
    buf.append("Content-Type: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDisposition();
    buf.append(prefix);
    buf.append("Content-Disposition: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDescription();
    buf.append(prefix);
    buf.append("Content-Description: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = MessageUtilities.getFileName(part);
    buf.append(prefix);
    buf.append("Content-Filename: ");
    buf.append(xvalue);
    buf.append('\n');

    if (part instanceof MimePart) {
        MimePart xmpart = (MimePart) part;
        xvalue = xmpart.getContentID();
        buf.append(prefix);
        buf.append("Content-ID: ");
        buf.append(xvalue);
        buf.append('\n');

        String[] langs = xmpart.getContentLanguage();

        if (langs != null) {
            buf.append(prefix);
            buf.append("Content-Language: ");

            for (int pi = 0; pi < langs.length; ++pi) {
                if (pi > 0) {
                    buf.append(", ");
                }

                buf.append(xvalue);
            }

            buf.append('\n');
        }

        xvalue = xmpart.getContentMD5();
        buf.append(prefix);
        buf.append("Content-MD5: ");
        buf.append(xvalue);
        buf.append('\n');

        xvalue = xmpart.getEncoding();
        buf.append(prefix);
        buf.append("Content-Encoding: ");
        buf.append(xvalue);
        buf.append('\n');
    }

    buf.append('\n');

    if (recurse && xctype.match("multipart/*")) {
        Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part);

        int xparts = xmulti.getCount();

        for (int xindex = 0; xindex < xparts; xindex++) {
            MessageUtilities.getPartDescription(xmulti.getBodyPart(xindex), buf, (prefix + "   "), true);
        }
    }

    return buf;
}

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

private void dumpPart(Part p, Element msg, Document doc) throws Exception {
    Element content = null;//from  w  w w  .j  a  v  a2 s  .c om
    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:net.wastl.webmail.server.WebMailSession.java

/**
   Use depth-first search to go through MIME-Parts recursively.
   @param p Part to begin with//ww  w  .ja va  2  s  .  co m
*/
protected void parseMIMEContent(Part p, XMLMessagePart parent_part, String msgid) throws MessagingException {
    StringBuilder content = new StringBuilder(1000);
    XMLMessagePart xml_part;
    try {
        if (p.getContentType().toUpperCase().startsWith("TEXT/HTML")) {
            /* The part is a text in HTML format. We will try to use "Tidy" to create a well-formatted
               XHTML DOM from it and then remove JavaScript and other "evil" stuff.
               For replying to such a message, it will be useful to just remove all of the tags and display
               only the text.
            */

            xml_part = parent_part.createPart("html");

            /****************************************************
             * LEAVING THESE OLD XML PARSERS COMMENTED OUT
             * until know that the new Parser tactic parses HTML properly
             * (or adequately).  See the ** comment below.
            /* Here we create a DOM tree.
            //Tidy tidy=new Tidy();
            //tidy.setUpperCaseTags(true);
            //Document htmldoc=tidy.parseDOM(p.getInputStream(),null);
            //              org.cyberneko.html.parsers.DOMParser parser =
            //                  new org.cyberneko.html.parsers.DOMParser();
            //              DOMParser parser = new DOMParser(new HTMLConfiguration());
            //              parser.parse(new InputSource(p.getInputStream()));
            //              Document htmldoc = parser.getDocument();
                    
            // instantiate a DOM implementation
            DOM dom = new com.docuverse.dom.DOM();
            // install the SAX driver for Swing HTML parser
            dom.setProperty("sax.driver", "com.docuverse.html.swing.SAXDriver");
                    
            // install HTML element factory
            dom.setFactory(new com.docuverse.dom.html.HTMLFactory());
            // ** N.B.  WITH docuverse AND NekoHTML, THE PARSER WAS
            // HTML-Specific.  We are now using generic XML parser.
            // Is that adequate?
                    
            // now just open the document
            Document htmldoc = (Document)dom.readDocument(p.getInputStream());
            */
            javax.xml.parsers.DocumentBuilder parser = javax.xml.parsers.DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document htmldoc = parser.parse(p.getInputStream());

            if (htmldoc == null) {
                log.error("Document was null!");
                // Why not throwing?
            }

            //dom.writeDocument(htmldoc,"/tmp/test.xml");

            /* Now let's look for all the malicious JavaScript and other <SCRIPT> tags,
               URLS containing the "javascript:" and tags containing "onMouseOver" and such
               stuff. */
            //              if(user.getBoolVar("filter javascript")) new JavaScriptCleaner(htmldoc);
            new JavaScriptCleaner(htmldoc);

            //dom.writeDocument(htmldoc,"/tmp/test2.xml");

            //XMLCommon.debugXML(htmldoc);
            /* HTML doesn't allow us to do such fancy stuff like different quote colors,
               perhaps this will be implemented in the future */

            /* So we just add this HTML document to the message part, which will deal with
               removing headers and tags that we don't need */
            xml_part.addContent(htmldoc);

        } else if (p.getContentType().toUpperCase().startsWith("TEXT")
                || p.getContentType().toUpperCase().startsWith("MESSAGE")) {
            /* The part is a standard message part in some incarnation of
               text (html or plain).  We should decode it and take care of
               some extra issues like recognize quoted parts, filter
               JavaScript parts and replace smileys with smiley-icons if the
               user has set wantsFancy() */

            xml_part = parent_part.createPart("text");
            // TODO:
            log.debug("text hit");

            BufferedReader in;
            if (p instanceof MimeBodyPart) {
                int size = p.getSize();
                MimeBodyPart mpb = (MimeBodyPart) p;
                InputStream is = mpb.getInputStream();

                /* Workaround for Java or Javamail Bug */
                is = new BufferedInputStream(is);
                ByteStore ba = ByteStore.getBinaryFromIS(is, size);
                in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(ba.getBytes())));
                /* End of workaround */
                size = is.available();

            } else {
                in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            }

            log.debug("Content-Type: " + p.getContentType());

            String token = "";
            int quote_level = 0, old_quotelevel = 0;
            boolean javascript_mode = false;
            /* Read in the message part line by line */
            while ((token = in.readLine()) != null) {
                /* First decode all language and MIME dependant stuff */
                // Default to ISO-8859-1 (Western Latin 1)
                String charset = "ISO-8859-1";

                // Check whether the part contained a charset in the content-type header
                StringTokenizer tok2 = new StringTokenizer(p.getContentType(), ";=");
                String blah = tok2.nextToken();
                if (tok2.hasMoreTokens()) {
                    blah = tok2.nextToken().trim();
                    if (blah.toLowerCase().equals("charset") && tok2.hasMoreTokens()) {
                        charset = tok2.nextToken().trim();
                    }
                }

                try {
                    token = new String(token.getBytes(), charset);
                } catch (UnsupportedEncodingException ex1) {
                    log.info("Java Engine does not support charset " + charset
                            + ". Trying to convert from MIME ...");

                    try {
                        charset = MimeUtility.javaCharset(charset);
                        token = new String(token.getBytes(), charset);

                    } catch (UnsupportedEncodingException ex) {
                        log.warn("Converted charset (" + charset
                                + ") does not work. Using default charset (ouput may contain errors)");
                        token = new String(token.getBytes());
                    }
                }

                /* Here we figure out which quote level this line has, simply by counting how many
                   ">" are in front of the line, ignoring all whitespaces. */
                int current_quotelevel = Helper.getQuoteLevel(token);

                /* When we are in a different quote level than the last line, we append all we got
                   so far to the part with the old quotelevel and begin with a clean String buffer */
                if (current_quotelevel != old_quotelevel) {
                    xml_part.addContent(content.toString(), old_quotelevel);
                    old_quotelevel = current_quotelevel;
                    content = new StringBuilder(1000);
                }

                if (user.wantsBreakLines()) {
                    Enumeration enumVar = Helper.breakLine(token, user.getMaxLineLength(), current_quotelevel);

                    while (enumVar.hasMoreElements()) {
                        String s = (String) enumVar.nextElement();
                        if (user.wantsShowFancy()) {
                            content.append(Fancyfier.apply(s)).append("\n");
                        } else {
                            content.append(s).append("\n");
                        }
                    }
                } else {
                    if (user.wantsShowFancy()) {
                        content.append(Fancyfier.apply(token)).append("\n");
                    } else {
                        content.append(token).append("\n");
                    }
                }
            }
            xml_part.addContent(content.toString(), old_quotelevel);
            // Why the following code???
            content = new StringBuilder(1000);
        } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/ALTERNATIVE")) {
            /* This is a multipart/alternative part. That means that we should pick one of
               the formats and display it for this part. Our current precedence list is
               to choose HTML first and then to choose plain text. */
            MimeMultipart m = (MimeMultipart) p.getContent();
            String[] preferred = { "TEXT/HTML", "TEXT" };
            boolean found = false;
            int alt = 0;
            // Walk though our preferred list of encodings. If we have found a fitting part,
            // decode it and replace it for the parent (this is what we really want with an
            // alternative!)
            /**
            findalt: while(!found && alt < preferred.length) {
            for(int i=0;i<m.getCount();i++) {
            Part p2=m.getBodyPart(i);
            if(p2.getContentType().toUpperCase().startsWith(preferred[alt])) {
                parseMIMEContent(p2,parent_part,msgid);
                found=true;
                break findalt;
            }
            }
            alt++;
            }
            **/
            /**
             * When user try to reply a mail, there may be 3 conditions:
             * 1. only TEXT exists.
             * 2. both HTML and TEXT exist.
             * 3. only HTML exists.
             *
             * We have to choose which part should we quote, that is, we must
             * decide the prority of parts to quote. Since quoting HTML is not
             * easy and precise (consider a html: <body><div><b>some text..</b>
             * </div></body>. Even we try to get text node under <body>, we'll
             * just get nothing, because "some text..." is marked up by
             * <div><b>. There is no easy way to retrieve text from html
             * unless we parse the html to analyse its semantics.
             *
             * Here is our policy for alternative part:
             * 1. Displays HTML but hides TEXT.
             * 2. When replying this mail, try to quote TEXT part. If no TEXT
             *    part exists, quote HTML in best effort(use
             *    XMLMessagePart.quoteContent() by Sebastian Schaffert.)
             */
            while (alt < preferred.length) {
                for (int i = 0; i < m.getCount(); i++) {
                    Part p2 = m.getBodyPart(i);
                    if (p2.getContentType().toUpperCase().startsWith(preferred[alt])) {
                        log.debug("Processing: " + p2.getContentType());
                        parseMIMEContent(p2, parent_part, msgid);
                        found = true;
                        break;
                    }
                }
                /**
                 * If we've selected HTML part from alternative part, the TEXT
                 * part should be hidden from display but keeping in XML for
                 * later quoting operation.
                 *
                 * Of course, this requires some modification on showmessage.xsl.
                 */
                if (found && (alt == 1)) {
                    Node textPartNode = parent_part.getPartElement().getLastChild();
                    NamedNodeMap attributes = textPartNode.getAttributes();
                    boolean hit = false;

                    for (int i = 0; i < attributes.getLength(); ++i) {
                        Node attr = attributes.item(i);
                        // If type=="TEXT", add a hidden attribute.
                        if (attr.getNodeName().toUpperCase().equals("TYPE")
                                && attr.getNodeValue().toUpperCase().equals("TEXT")) {
                            ((Element) textPartNode).setAttribute("hidden", "true");
                        }
                    }
                }
                alt++;
            }
            if (!found) {
                // If we didn't find one of our preferred encodings, choose the first one
                // simply pass the parent part because replacement is what we really want with
                // an alternative.
                parseMIMEContent(m.getBodyPart(0), parent_part, msgid);
            }

        } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/")) {
            /* This is a standard multipart message. We should recursively walk thorugh all of
               the parts and decode them, appending as children to the current part */

            xml_part = parent_part.createPart("multi");

            MimeMultipart m = (MimeMultipart) p.getContent();
            for (int i = 0; i < m.getCount(); i++) {
                parseMIMEContent(m.getBodyPart(i), xml_part, msgid);
            }
        } else {
            /* Else treat the part as a binary part that the user should either download or
               get displayed immediately in case of an image */
            InputStream in = null;
            String type = "";
            if (p.getContentType().toUpperCase().startsWith("IMAGE/JPG")
                    || p.getContentType().toUpperCase().startsWith("IMAGE/JPEG")) {
                type = "jpg";
                xml_part = parent_part.createPart("image");
            } else if (p.getContentType().toUpperCase().startsWith("IMAGE/GIF")) {
                type = "gif";
                xml_part = parent_part.createPart("image");
            } else if (p.getContentType().toUpperCase().startsWith("IMAGE/PNG")) {
                type = "png";
                xml_part = parent_part.createPart("image");
            } else {
                xml_part = parent_part.createPart("binary");
            }
            int size = p.getSize();
            if (p instanceof MimeBodyPart) {
                MimeBodyPart mpb = (MimeBodyPart) p;
                log.debug("MIME Body part (image), Encoding: " + mpb.getEncoding());
                InputStream is = mpb.getInputStream();

                /* Workaround for Java or Javamail Bug */
                in = new BufferedInputStream(is);
                ByteStore ba = ByteStore.getBinaryFromIS(in, size);
                in = new ByteArrayInputStream(ba.getBytes());
                /* End of workaround */
                size = in.available();

            } else {
                log.warn("No MIME Body part!!");
                // Is this unexpected?  Consider changing log level.
                in = p.getInputStream();
            }

            ByteStore data = ByteStore.getBinaryFromIS(in, size);
            if (mime_parts_decoded == null) {
                mime_parts_decoded = new HashMap<String, ByteStore>();
            }
            String name = p.getFileName();
            if (name == null || name.equals("")) {
                // Try an other way
                String headers[] = p.getHeader("Content-Disposition");
                int pos = -1;
                if (headers.length == 1) {
                    pos = headers[0].indexOf("filename*=") + 10;
                }
                if (pos != -1) {
                    int charsetEnds = headers[0].indexOf("''", pos);
                    String charset = headers[0].substring(pos, charsetEnds);
                    String encodedFileName = headers[0].substring(charsetEnds + 2);
                    encodedFileName = "=?" + charset + "?Q?" + encodedFileName.replace('%', '=') + "?=";
                    name = MimeUtility.decodeText(encodedFileName);
                } else {
                    name = "unknown." + type;
                }
            }
            // Eliminate space characters. Should do some more things in the future
            name = name.replace(' ', '_');
            data.setContentType(p.getContentType());
            data.setContentEncoding("BINARY");
            mime_parts_decoded.put(msgid + "/" + name, data);

            /**
             * For multibytes language system, we have to separate filename into
             * 2 format: one for display (UTF-8 encoded), another for encode the
             * url of hyperlink.
             * `filename' is for display, while `hrefFileName' is for hyperlink.
             * To make use of these two attributes, `showmessage.xsl' is slightly
             * modified.
             */
            data.setName(name);
            xml_part.setAttribute("filename", name);
            // Transcode name into UTF-8 bytes then make a new ISO8859_1 string to encode URL.
            xml_part.setAttribute("hrefFileName", name);
            xml_part.setAttribute("size", size + "");
            String description = p.getDescription() == null ? "" : p.getDescription();
            xml_part.setAttribute("description", description);
            StringTokenizer tok = new StringTokenizer(p.getContentType(), ";");
            xml_part.setAttribute("content-type", tok.nextToken().toLowerCase());
        }
    } catch (java.io.IOException ex) {
        log.error("Failed to parse mime content", ex);
    } catch (MessagingException ex) {
        log.error("Failed to parse mime content", ex);
    } catch (Exception ex) {
        log.error("Failed to parse mime content", ex);
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected void extractAttachmentsFromMultipart(Multipart mp, Map<String, DataHandler> map)
        throws javax.mail.MessagingException, IOException {

    for (int i = 0; i < mp.getCount(); i++) {
        Part part = mp.getBodyPart(i);
        LOG.trace("Part #" + i + ": " + part);

        if (part.isMimeType("multipart/*")) {
            LOG.trace("Part #" + i + ": is mimetype: multipart/*");
            extractAttachmentsFromMultipart((Multipart) part.getContent(), map);
        } else {/*from  www.  j a  v  a  2  s . c  o  m*/
            String disposition = part.getDisposition();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Part #" + i + ": Disposition: " + part.getDisposition());
                LOG.trace("Part #" + i + ": Description: " + part.getDescription());
                LOG.trace("Part #" + i + ": ContentType: " + part.getContentType());
                LOG.trace("Part #" + i + ": FileName: " + part.getFileName());
                LOG.trace("Part #" + i + ": Size: " + part.getSize());
                LOG.trace("Part #" + i + ": LineCount: " + part.getLineCount());
            }

            if (disposition != null && (disposition.equalsIgnoreCase(Part.ATTACHMENT)
                    || disposition.equalsIgnoreCase(Part.INLINE))) {
                // only add named attachments
                String fileName = part.getFileName();
                if (fileName != null) {
                    LOG.debug("Mail contains file attachment: " + fileName);
                    // Parts marked with a disposition of Part.ATTACHMENT are clearly attachments
                    CollectionHelper.appendValue(map, fileName, part.getDataHandler());
                }
            }
        }
    }
}

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.RFC822ToTextConverter.java

protected Blob extractTextFromMessage(Blob blob) {
    if (blob == null) {
        return null;
    }//from w  w w .j  a v  a  2  s  .c  o  m
    File f = null;
    OutputStream fo = null;
    try {
        MimeMessage msg = new MimeMessage((Session) null, blob.getStream());
        f = File.createTempFile("rfc822totext", ".txt");
        fo = new FileOutputStream(f);
        List<Part> parts = getAttachmentParts(msg);
        writeInfo(fo, msg.getSubject());
        writeInfo(fo, msg.getFrom());
        writeInfo(fo, msg.getRecipients(RecipientType.TO));
        writeInfo(fo, msg.getRecipients(RecipientType.CC));
        for (Part part : parts) {
            writeInfo(fo, part.getFileName());
            writeInfo(fo, part.getDescription());
            byte[] extracted = extractTextFromMessagePart(part);
            if (extracted != null) {
                writeInfo(fo, extracted);
            }
        }
        Blob outblob = new FileBlob(new FileInputStream(f));
        outblob.setMimeType(descriptor.getDestinationMimeType());
        return outblob;
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (fo != null) {
            try {
                fo.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
        if (f != null) {
            f.delete();
        }
    }
    return null;
}