Example usage for javax.mail.internet MimeBodyPart getEncoding

List of usage examples for javax.mail.internet MimeBodyPart getEncoding

Introduction

In this page you can find the example usage for javax.mail.internet MimeBodyPart getEncoding.

Prototype

@Override
public String getEncoding() throws MessagingException 

Source Link

Document

Returns the content transfer encoding from the "Content-Transfer-Encoding" header field.

Usage

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/*  w  w  w.  j a va  2 s .c  o 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.campware.cream.modules.scheduledjobs.Pop3Job.java

private void saveAttachment(Part part, InboxEvent inboxentry) throws Exception {

    MimeBodyPart mbp = (MimeBodyPart) part;
    String fileName = mbp.getFileName();
    String fileType = mbp.getContentType();
    String fileId = mbp.getContentID();
    String fileEncoding = mbp.getEncoding();
    String attContent;// w  ww .ja v a  2  s.c  om

    if (fileName == null || fileName.length() < 2) {
        fileName = new String("Unknown");
        if (fileType.indexOf("name") > 0) {
            int i = fileType.indexOf("name");
            int j = fileType.indexOf("\"", i + 1);
            if (j != -1) {
                int k = fileType.indexOf("\"", j + 1);
                if (k != -1) {
                    fileName = fileType.substring(j + 1, k);
                }

            } else {
                int k = fileType.indexOf(";", i + 1);
                if (k != -1) {
                    fileName = fileType.substring(i + 5, k);

                } else {
                    fileName = fileType.substring(i + 5, fileType.length());
                }

            }
        }
    }

    InboxAttachment entryItem = new InboxAttachment();

    entryItem.setFileName(fileName);
    if (fileType != null)
        entryItem.setContentType(fileType);

    if (mbp.getContent() instanceof InputStream) {
        InputStream is = new Base64.InputStream(mbp.getInputStream(), Base64.ENCODE);

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        StringBuffer att = new StringBuffer();
        String thisLine = reader.readLine();

        while (thisLine != null) {
            att.append(thisLine);
            thisLine = reader.readLine();
        }

        attContent = att.toString();
        //           MimeUtility.encode(part.getOutputStream(), "base64");
        //           attachments += saveFile(part.getFileName(), part.getInputStream());

    } else {
        attContent = part.getContent().toString();
    }

    entryItem.setContent(attContent);
    entryItem.setContentId(fileId);

    inboxentry.addInboxAttachment(entryItem);

}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public ShsMessage unmarshal(InputStream stream) throws IllegalMessageStructureException {
    log.trace("unmarshal(InputStream)");

    try {/*from w ww  .j  ava 2s.c om*/
        stream = SharedDeferredStream.toSharedInputStream(stream);
        MimeMessage mimeMessage = new MimeMessage(session, stream);
        Object msgContent = mimeMessage.getContent();

        if (!(msgContent instanceof MimeMultipart)) {
            throw new IllegalMessageStructureException(
                    "Expected a multipart mime message, got " + msgContent.getClass());
        }

        MimeMultipart multipart = (MimeMultipart) msgContent;

        if (multipart.getCount() < 2) {
            throw new IllegalMessageStructureException("SHS message must contain at least two mime bodyparts");
        }

        ShsMessage shsMessage = new ShsMessage();

        BodyPart labelPart = multipart.getBodyPart(0);
        if (!labelPart.isMimeType("text/xml") && !labelPart.isMimeType("text/plain")) {
            throw new IllegalMessageStructureException(
                    "First bodypart is not text/xml nor text/plain but was " + labelPart.getContentType());
        }

        ShsLabel label = shsLabelMarshaller.unmarshal((String) labelPart.getContent());

        shsMessage.setLabel(label);

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("Label contains no content elements");
        }

        // this reads only as many mime body parts as there are content/data elements in the label
        int i = 1;
        for (Object o : content.getDataOrCompound()) {
            MimeBodyPart dp = (MimeBodyPart) multipart.getBodyPart(i);
            DataHandler dh = dp.getDataHandler();
            DataPart dataPart = new DataPart();
            dataPart.setDataHandler(new DataHandler(
                    new InputStreamDataSource(dh.getDataSource().getInputStream(), dh.getContentType())));

            dataPart.setContentType(dh.getContentType());

            String encoding = dp.getEncoding();
            if (encoding != null) {
                dataPart.setTransferEncoding(encoding);
            }

            dataPart.setFileName(dp.getFileName());

            if (o instanceof Data) {
                Data data = (Data) o;
                dataPart.setDataPartType(data.getDatapartType());
            } else if (o instanceof Compound) {
                continue;
            }
            shsMessage.addDataPart(dataPart);
            i++;
        }

        return shsMessage;

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }

        throw new IllegalMessageStructureException(e);
    }
}