Example usage for javax.mail Part getAllHeaders

List of usage examples for javax.mail Part getAllHeaders

Introduction

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

Prototype

public Enumeration<Header> getAllHeaders() throws MessagingException;

Source Link

Document

Return all the headers from this part as an Enumeration of Header objects.

Usage

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

/**
 * Given a message that we are replying to, or forwarding,
 *
 * @param part The part to decode./*from www.j av a2 s  . c om*/
 * @param buffer The new message body text buffer.
 * @param dmailParts Vector for new message's attachments.
 *
 * @return The buffer being filled in with the body.
 *
 * @throws MessagingException DOCUMENT ME!
 * @throws IOException
 */
protected static StringBuffer subDecodeContent(Part part, StringBuffer buffer, Vector dmailParts,
        boolean chooseHtml, String breakLine) throws MessagingException, IOException {
    boolean attachIt = true;

    // decode based on content type and disposition
    ContentType xctype = MessageUtilities.getContentType(part);

    ContentDisposition xcdisposition = MessageUtilities.getContentDisposition(part);

    if (xctype.match("multipart/*")) {
        attachIt = false;

        Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part);

        int xparts = 0;

        try {
            xparts = xmulti.getCount();
        } catch (MessagingException e) {
            attachIt = true;
            xparts = 0;
        }

        for (int xindex = 0; xindex < xparts; xindex++) {
            MessageUtilities.subDecodeContent(xmulti.getBodyPart(xindex), buffer, dmailParts, chooseHtml,
                    breakLine);
        }
    } else if (xctype.match("message/rfc822")) {
        MimeMessage newMessage = new MimeMessage((Session) null, part.getInputStream());
        decodeContent(newMessage, buffer, dmailParts, chooseHtml, breakLine);
    } else if (xctype.match("text/plain") && !chooseHtml) {
        if (xcdisposition.match("inline")) {
            attachIt = false;

            String xjcharset = xctype.getParameter("charset");

            if (xjcharset == null) {
                // not present, assume ASCII character encoding                       
                try {
                    Header xheader;
                    Enumeration xe = part.getAllHeaders();

                    for (; xe.hasMoreElements();) {
                        xheader = (Header) xe.nextElement();

                        String aux = xheader.getName().toLowerCase().trim();

                        if (aux.indexOf("subject") > -1) {
                            int pos1 = aux.indexOf("=?");
                            int pos2 = aux.indexOf("?q?");

                            if ((pos1 > -1) && (pos2 > -1)) {
                                xjcharset = aux.substring(pos1, pos2);
                            }

                            break;
                        }
                    }
                } catch (Exception ex) {
                    System.out.print(ex.getMessage());
                }

                if (xjcharset == null) {
                    xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms
                }
            }

            MessageUtilities.decodeTextPlain(buffer, part, breakLine, xjcharset);
        }
    } else if (xctype.match("text/html") && chooseHtml) {
        if (xcdisposition.match("inline")) {
            attachIt = false;

            String xjcharset = xctype.getParameter("charset");

            if (xjcharset == null) {
                // not present, assume ASCII character encoding                       
                try {
                    Header xheader;
                    Enumeration xe = part.getAllHeaders();

                    for (; xe.hasMoreElements();) {
                        xheader = (Header) xe.nextElement();

                        String aux = xheader.getName().toLowerCase().trim();

                        if (aux.indexOf("subject") > -1) {
                            int pos1 = aux.indexOf("=?");
                            int pos2 = aux.indexOf("?q?");

                            if ((pos1 > -1) && (pos2 > -1)) {
                                xjcharset = aux.substring(pos1, pos2);
                            }

                            break;
                        }
                    }
                } catch (Exception ex) {
                }

                if (xjcharset == null) {
                    xjcharset = Charset.defaultCharset().displayName(); // US-ASCII in JAVA terms
                }
            }

            MessageUtilities.decodeTextHtml(buffer, part, xjcharset);
        }
    }

    if (attachIt) {
        // UNDONE should simple single line entries be
        //        created for other types and attachments?
        //
        // UNDONE should attachements only be created for "attachments" or all
        // unknown content types?
        if (dmailParts != null) {
            MailPart aux = new MailPart();
            aux.setPart(part);
            aux.setId(dmailParts.size());
            aux.setName(MessageUtilities.encodeStringToXml(MessageUtilities.getPartName(part)));
            aux.setContentType(xctype.getBaseType());
            aux.setSize(part.getSize());

            dmailParts.addElement(aux);
        }
    }

    return buffer;
}

From source file:edu.stanford.muse.email.EmailFetcherStats.java

/**
 * this method returns the text content of the message as a list of strings
 * // each element of the list could be the content of a multipart message
 * // m is the top level subject//from  w  ww  .j  a  v  a2  s . c o  m
 * // p is the specific part that we are processing (p could be == m)
 * also sets up names of attachments (though it will not download the
 * attachment unless downloadAttachments is true)
 */
private List<String> processMessagePart(int messageNum, Message m, Part p, List<Blob> attachmentsList)
        throws MessagingException, IOException {
    List<String> list = new ArrayList<String>(); // return list
    if (p == null) {
        dataErrors.add("part is null: " + folder_name() + " idx " + messageNum);
        return list;
    }

    if (p == m && p.isMimeType("text/html")) {
        /*
        String s = "top level part is html! message:" + m.getSubject() + " " + m.getDescription();
        dataErrors.add(s);
        */
        // we don't normally expect the top-level part to have content-type text/html
        // but we saw this happen on some sample archives pst -> emailchemy. so allow it and handle it by parsing the html
        String html = (String) p.getContent();
        String text = Util.unescapeHTML(html);
        org.jsoup.nodes.Document doc = Jsoup.parse(text);

        StringBuilder sb = new StringBuilder();
        HTMLUtils.extractTextFromHTML(doc.body(), sb);
        list.add(sb.toString());
        return list;
    }

    if (p.isMimeType("text/plain")) {
        //make sure, p is not wrongly labelled as plain text.
        Enumeration headers = p.getAllHeaders();
        boolean dirty = false;
        if (headers != null)
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                String name = h.getName();
                String value = h.getValue();
                if (name != null && value != null) {
                    if (name.equals("Content-transfer-encoding") && value.equals("base64")) {
                        dirty = true;
                        break;
                    }
                }
            }
        String fname = p.getFileName();
        if (fname != null) {
            int idx = fname.lastIndexOf('.');
            if ((idx < fname.length()) && (idx >= 0)) {
                String extension = fname.substring(idx);
                //anything extension other than .txt is suspicious.
                if (!extension.equals(".txt"))
                    dirty = true;
            }
        }
        if (dirty) {
            dataErrors.add("Dirty message part, has conflicting message part headers." + folder_name()
                    + " Message# " + messageNum);
            return list;
        }

        log.debug("Message part with content type text/plain");
        String content;
        String type = p.getContentType(); // new InputStreamReader(p.getInputStream(), "UTF-8");
        try {
            // if forced encoding is set, we read the string with that encoding, otherwise we just use whatever p.getContent gives us
            if (FORCED_ENCODING != null) {
                byte b[] = Util.getBytesFromStream(p.getInputStream());
                content = new String(b, FORCED_ENCODING);
            } else
                content = (String) p.getContent();
        } catch (UnsupportedEncodingException uee) {
            dataErrors.add("Unsupported encoding: " + folder_name() + " Message #" + messageNum + " type "
                    + type + ", using brute force conversion");
            // a particularly nasty issue:javamail can't handle utf-7 encoding which is common with hotmail and exchange servers.
            // we're using the workaround suggested on this page: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4304013
            // though it may be better to consider official support for utf-7 or other encodings.

            // TOFIX: I get an exception for utfutf8-encoding which has a base64 encoding embedded on it.
            // Unsupported encoding: gmail-sent Message #10477 type text/plain; charset=x-utf8utf8; name="newyorker.txt",
            // the hack below doesn't work for it.
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            p.writeTo(bao);
            content = bao.toString();
        }
        list.add(content);
    } else if (p.isMimeType("multipart/*") || p.isMimeType("message/rfc822")) {
        // rfc822 mime type is for embedded mbox format or some such (appears for things like
        // forwarded messages). the content appears to be just a multipart.
        Object o = p.getContent();
        if (o instanceof Multipart) {
            Multipart allParts = (Multipart) o;
            if (p.isMimeType("multipart/alternative")) {
                // this is an alternative mime type. v common case to have text and html alternatives
                // so just process the text part if there is one, and avoid fetching the alternatives.
                // useful esp. because many ordinary messages are alternative: text and html and we don't want to fetch the html.
                // revisit in future we want to retain the html alternative for display purposes
                Part[] parts = new Part[allParts.getCount()];
                for (int i = 0; i < parts.length; i++)
                    parts[i] = allParts.getBodyPart(i);

                for (int i = 0; i < parts.length; i++) {
                    Part thisPart = parts[i];
                    if (thisPart.isMimeType("text/plain")) {
                        // common case, return quickly
                        list.add((String) thisPart.getContent());
                        log.debug("Multipart/alternative with content type text/plain");
                        return list;
                    }
                }

                // no text part, let's look for an html part. this happens for html parts.
                for (int i = 0; i < allParts.getCount(); i++) {
                    Part thisPart = parts[i];
                    if (thisPart.isMimeType("text/html")) {
                        // common case, return quickly
                        String html = (String) thisPart.getContent();
                        String text = Util.unescapeHTML(html);
                        org.jsoup.nodes.Document doc = Jsoup.parse(text);

                        StringBuilder sb = new StringBuilder();
                        HTMLUtils.extractTextFromHTML(doc.body(), sb);
                        list.add(sb.toString());

                        log.debug("Multipart/alternative with content type text/html");
                        return list;
                    }
                }

                // no text or html part. hmmm... blindly process the first part only
                if (allParts.getCount() >= 1)
                    list.addAll(processMessagePart(messageNum, m, allParts.getBodyPart(0), attachmentsList));
            } else {
                // process it like a regular multipart
                for (int i = 0; i < allParts.getCount(); i++) {
                    BodyPart bp = allParts.getBodyPart(i);
                    list.addAll(processMessagePart(messageNum, m, bp, attachmentsList));
                }
            }
        } else if (o instanceof Part)
            list.addAll(processMessagePart(messageNum, m, (Part) o, attachmentsList));
        else
            dataErrors.add("Unhandled part content, " + folder_name() + " Message #" + messageNum
                    + "Java type: " + o.getClass() + " Content-Type: " + p.getContentType());
    } else {
        try {
            // do attachments only if downloadAttachments is set.
            // some apps do not need attachments, so this saves some time.
            // however, it seems like a lot of time is taken in imap prefetch, which gets attachments too?
            if (fetchConfig.downloadAttachments)
                handleAttachments(messageNum, m, p, list, attachmentsList);
        } catch (Exception e) {
            dataErrors.add("Ignoring attachment for " + folder_name() + " Message #" + messageNum + ": "
                    + Util.stackTrace(e));
        }
    }

    return list;
}

From source file:org.mule.transport.email.MailMuleMessageFactory.java

protected void addAttachmentHeaders(String name, Part part, MuleMessage muleMessage)
        throws javax.mail.MessagingException {
    Map<String, String> headers = new HashMap<String, String>();
    for (Enumeration<?> e = part.getAllHeaders(); e.hasMoreElements();) {
        Header h = (Header) e.nextElement();
        headers.put(h.getName(), h.getValue());
    }/*  w w  w.  ja  v a 2s.  c om*/

    if (headers.size() > 0) {
        muleMessage.setProperty(name + AbstractMailConnector.ATTACHMENT_HEADERS_PROPERTY_POSTFIX, headers,
                PropertyScope.INBOUND);
    }
}