Example usage for javax.mail.internet MimeUtility decodeText

List of usage examples for javax.mail.internet MimeUtility decodeText

Introduction

In this page you can find the example usage for javax.mail.internet MimeUtility decodeText.

Prototype

public static String decodeText(String etext) throws UnsupportedEncodingException 

Source Link

Document

Decode "unstructured" headers, that is, headers that are defined as '*text' as per RFC 822.

Usage

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

public static String getFromInetAddressForBroken(MimeMessage msg) {
    String rawFrom = getRawFrom(msg);
    String inetAddress = null;/*  w  w w.  j a v a2s  .com*/
    try {
        inetAddress = MimeUtility.decodeText(MimeUtility.unfold(rawFrom));
    } catch (UnsupportedEncodingException ignore) {
    }
    return null != inetAddress ? inetAddress : "";
}

From source file:com.zimbra.cs.service.mail.ToXML.java

private static Element addPart(VisitPhase phase, Element parent, Element root, MPartInfo mpi,
        Set<MPartInfo> bodies, String prefix, int maxSize, boolean neuter, boolean excludeCalendarParts,
        String defaultCharset, boolean swallowContentExceptions, MsgContent wantContent)
        throws ServiceException {
    if (phase == VisitPhase.POSTVISIT) {
        return null;
    }//from w ww  .ja v  a  2s  .c o  m
    String ctype = StringUtil.stripControlCharacters(mpi.getContentType());

    if (excludeCalendarParts && MimeConstants.CT_TEXT_CALENDAR.equalsIgnoreCase(ctype)) {
        // A true calendar part has "method" parameter in the content type.  Otherwise it's just an attachment
        // that happens to be a .ics file.
        try {
            ContentType ct = new ContentType(mpi.getMimePart().getContentType());
            if (ct.getParameter("method") != null) {
                return null;
            }
        } catch (MessagingException e) {
        }
    }

    Element el = parent.addNonUniqueElement(MailConstants.E_MIMEPART);
    MimePart mp = mpi.getMimePart();

    String part = mpi.getPartName();
    part = prefix + (prefix.isEmpty() || part.isEmpty() ? "" : ".") + part;
    el.addAttribute(MailConstants.A_PART, part);

    String fname = Mime.getFilename(mp);
    if (MimeConstants.CT_XML_ZIMBRA_SHARE.equals(ctype)) {
        // the <shr> share info goes underneath the top-level <m>
        Element shr = root.addNonUniqueElement(MailConstants.E_SHARE_NOTIFICATION);
        try {
            addContent(shr, mpi, maxSize, defaultCharset);
        } catch (IOException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing share XML", e);
            } else {
                LOG.warn("error writing body part", e);
            }
        } catch (MessagingException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing share XML", e);
            }
        }
    } else if (MimeConstants.CT_XML_ZIMBRA_DL_SUBSCRIPTION.equals(ctype)) {
        // the <dlSubs> dl subscription info goes underneath the top-level <m>
        Element dlSubs = root.addNonUniqueElement(MailConstants.E_DL_SUBSCRIPTION_NOTIFICATION);
        try {
            addContent(dlSubs, mpi, maxSize, defaultCharset);
        } catch (IOException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing DL subscription", e);
            } else {
                LOG.warn("error writing body part", e);
            }
        } catch (MessagingException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing DL subscription", e);
            }
        }
    } else if (MimeConstants.CT_TEXT_ENRICHED.equals(ctype)) {
        // we'll be replacing text/enriched with text/html
        ctype = MimeConstants.CT_TEXT_HTML;
    } else if (fname != null && (MimeConstants.CT_APPLICATION_OCTET_STREAM.equals(ctype)
            || MimeConstants.CT_APPLICATION_TNEF.equals(ctype))) {
        String guess = MimeDetect.getMimeDetect().detect(fname);
        if (guess != null) {
            ctype = guess;
        }
    }
    el.addAttribute(MailConstants.A_CONTENT_TYPE, ctype);

    if (mpi.isMultipart()) {
        return el; // none of the below stuff is relevant for a multipart, so just return now...
    }

    // figure out attachment size
    try {
        el.addAttribute(MailConstants.A_SIZE, Mime.getSize(mp));
    } catch (Exception e) { // don't put out size if we get exception
        ZimbraLog.mailbox.warn("Unable to determine MIME part size: %s", e.getMessage());
    }

    // figure out attachment disposition
    try {
        String disp = mp.getHeader("Content-Disposition", null);
        if (disp != null) {
            ContentDisposition cdisp = new ContentDisposition(MimeUtility.decodeText(disp));
            el.addAttribute(MailConstants.A_CONTENT_DISPOSITION,
                    StringUtil.stripControlCharacters(cdisp.getDisposition()));
        }
    } catch (MessagingException e) {
    } catch (UnsupportedEncodingException e) {
    }

    // figure out attachment name
    try {
        if (fname == null && MimeConstants.CT_MESSAGE_RFC822.equals(ctype)) {
            // "filename" for attached messages is the Subject
            Object content = Mime.getMessageContent(mp);
            if (content instanceof MimeMessage) {
                fname = Mime.getSubject((MimeMessage) content);
            }
        }
        if (!Strings.isNullOrEmpty(fname)) {
            el.addAttribute(MailConstants.A_CONTENT_FILENAME, StringUtil.stripControlCharacters(fname));
        }
    } catch (MessagingException me) {
    } catch (IOException ioe) {
    }

    // figure out content-id (used in displaying attached images)
    String cid = mpi.getContentID();
    if (cid != null) {
        el.addAttribute(MailConstants.A_CONTENT_ID, StringUtil.stripControlCharacters(cid));
    }
    // figure out content-location (used in displaying attached images)
    try {
        String cl = mp.getHeader("Content-Location", null);
        if (cl != null) {
            el.addAttribute(MailConstants.A_CONTENT_LOCATION, StringUtil.stripControlCharacters(cl));
        }
    } catch (MessagingException e) {
    }

    // include the part's content if this is the displayable "memo part",
    // or if it was requested to include all parts
    if (bodies == null || bodies.contains(mpi)) {
        if (bodies != null) {
            el.addAttribute(MailConstants.A_BODY, true);
        }

        try {
            addContent(el, mpi, maxSize, neuter, defaultCharset, wantContent);
        } catch (IOException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing part content", e);
            } else {
                LOG.warn("error writing body part", e);
            }
        } catch (MessagingException me) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing part content", me);
            }
        }
    }

    return el;
}

From source file:com.sonicle.webtop.mail.Service.java

public String getPartName(Part p) throws MessagingException {
    String pname = p.getFileName();
    // TODO: Remove code below if already included in JavaMail impl.
    if (pname == null) {
        String hctypes[] = p.getHeader("Content-Type");
        if (hctypes == null || hctypes.length == 0) {
            return null;
        }//w  w w  .  ja  va 2s. c  o  m
        String hctype = hctypes[0];
        int ix = hctype.indexOf("name=");
        if (ix >= 0) {
            int sx = ix + 5;
            int ex = hctype.indexOf(";", sx);
            if (ex >= 0) {
                pname = hctype.substring(sx, ex);
            } else {
                pname = hctype.substring(sx);
            }
            pname = pname.trim();
            int xx = pname.length() - 1;
            if (pname.charAt(0) == '"' && pname.charAt(xx) == '"') {
                pname = pname.substring(1, xx);
            }
        }
        if (pname == null) {
            return null;
        }
        logger.warn("Code in getPartName is still used. Please review it!");
        try {
            pname = MimeUtility.decodeText(pname);
        } catch (UnsupportedEncodingException ex) {
            Service.logger.error("Exception", ex);
        }
    }
    return pname;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Create a Message List./* ww w .  j a  va  2 s .com*/
 * Fetches a list of headers in folder foldername for part list_part.
 * The messagelist will be stored in the "MESSAGES" environment.
 *
 * @param foldername folder for which a message list should be built
 * @param list_part part of list to display (1 = last xx messages, 2 = total-2*xx - total-xx messages)
 */
public void createMessageList(String folderhash, int list_part) throws NoSuchFolderException {
    long time_start = System.currentTimeMillis();
    TimeZone tz = TimeZone.getDefault();
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
            user.getPreferredLocale());
    df.setTimeZone(tz);

    try {
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);
        Element xml_current = model.setCurrentFolder(folderhash);
        Element xml_messagelist = model.getMessageList(xml_folder);

        if (folder == null) {
            throw new NoSuchFolderException(folderhash);
        }

        long fetch_start = System.currentTimeMillis();

        if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        } else {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        }

        /* Calculate first and last message to show */
        int total_messages = folder.getMessageCount();
        int new_messages = folder.getNewMessageCount();
        int show_msgs = user.getMaxShowMessages();

        xml_messagelist.setAttribute("total", total_messages + "");
        xml_messagelist.setAttribute("new", new_messages + "");

        log.debug("Total: " + total_messages);

        /* Handle small messagelists correctly */
        if (total_messages < show_msgs) {
            show_msgs = total_messages;
        }
        /* Don't accept list-parts smaller than 1 */
        if (list_part < 1) {
            list_part = 1;
        }
        for (int k = 0; k < list_part; k++) {
            total_messages -= show_msgs;
        }
        /* Handle beginning of message list */
        if (total_messages < 0) {
            total_messages = 0;
        }
        int first = total_messages + 1;
        int last = total_messages + show_msgs;
        /* Set environment variable */
        setEnv();
        xml_current.setAttribute("first_msg", first + "");
        xml_current.setAttribute("last_msg", last + "");
        xml_current.setAttribute("list_part", list_part + "");

        /* Fetch headers */
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfile.Item.FLAGS);
        fp.add(FetchProfile.Item.CONTENT_INFO);
        log.debug("Last: " + last + ", first: " + first);
        Message[] msgs = folder.getMessages(first, last);
        log.debug(msgs.length + " messages fetching...");
        folder.fetch(msgs, fp);
        long fetch_stop = System.currentTimeMillis();

        Map header = new Hashtable(15);

        Flags.Flag[] sf;
        String from, to, cc, bcc, replyto, subject;
        String messageid;

        for (int i = msgs.length - 1; i >= 0; i--) {
            //              if(((MimeMessage)msgs[i]).getMessageID() == null) {
            //                  folder.close(false);
            //                  folder.open(Folder.READ_WRITE);
            //                  ((MimeMessage)msgs[i]).setHeader("Message-ID","<"+user.getLogin()+"."+System.currentTimeMillis()+".jwebmail@"+user.getDomain()+">");
            //                  ((MimeMessage)msgs[i]).saveChanges();
            //                  folder.close(false);
            //                  folder.open(Folder.READ_ONLY);
            //              }

            try {
                StringTokenizer tok = new StringTokenizer(((MimeMessage) msgs[i]).getMessageID(), "<>");
                messageid = tok.nextToken();
            } catch (NullPointerException ex) {
                // For mail servers that don't generate a Message-ID (Outlook et al)
                messageid = user.getLogin() + "." + i + ".jwebmail@" + user.getDomain();
            }

            XMLMessage xml_message = model.getMessage(xml_folder, msgs[i].getMessageNumber() + "", messageid);

            /* Addresses */
            from = "";
            replyto = "";
            to = "";
            cc = "";
            bcc = "";
            try {
                from = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getFrom()));
            } catch (UnsupportedEncodingException e) {
                from = Helper.joinAddress(msgs[i].getFrom());
            }
            try {
                replyto = MimeUtility.decodeText(Helper.joinAddress(msgs[i].getReplyTo()));
            } catch (UnsupportedEncodingException e) {
                replyto = Helper.joinAddress(msgs[i].getReplyTo());
            }
            try {
                to = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO)));
            } catch (UnsupportedEncodingException e) {
                to = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.TO));
            }
            try {
                cc = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC)));
            } catch (UnsupportedEncodingException e) {
                cc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.CC));
            }
            try {
                bcc = MimeUtility
                        .decodeText(Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC)));
            } catch (UnsupportedEncodingException e) {
                bcc = Helper.joinAddress(msgs[i].getRecipients(Message.RecipientType.BCC));
            }
            if (from == "")
                from = getStringResource("unknown sender");
            if (to == "")
                to = getStringResource("unknown recipient");

            /* Flags */
            sf = msgs[i].getFlags().getSystemFlags();
            String basepath = parent.getBasePath();

            for (int j = 0; j < sf.length; j++) {
                if (sf[j] == Flags.Flag.RECENT)
                    xml_message.setAttribute("recent", "true");
                if (sf[j] == Flags.Flag.SEEN)
                    xml_message.setAttribute("seen", "true");
                if (sf[j] == Flags.Flag.DELETED)
                    xml_message.setAttribute("deleted", "true");
                if (sf[j] == Flags.Flag.ANSWERED)
                    xml_message.setAttribute("answered", "true");
                if (sf[j] == Flags.Flag.DRAFT)
                    xml_message.setAttribute("draft", "true");
                if (sf[j] == Flags.Flag.FLAGGED)
                    xml_message.setAttribute("flagged", "true");
                if (sf[j] == Flags.Flag.USER)
                    xml_message.setAttribute("user", "true");
            }
            if (msgs[i] instanceof MimeMessage
                    && ((MimeMessage) msgs[i]).getContentType().toUpperCase().startsWith("MULTIPART/")) {
                xml_message.setAttribute("attachment", "true");
            }

            if (msgs[i] instanceof MimeMessage) {
                int size = ((MimeMessage) msgs[i]).getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");
            }

            /* Subject */
            subject = "";
            if (msgs[i].getSubject() != null) {
                try {
                    subject = MimeUtility.decodeText(msgs[i].getSubject());
                } catch (UnsupportedEncodingException ex) {
                    subject = msgs[i].getSubject();
                    log.warn("Unsupported Encoding: " + ex.getMessage());
                }
            }
            if (subject == null || subject.equals("")) {
                subject = getStringResource("no subject");
            }

            /* Set all of what we found into the DOM */
            xml_message.setHeader("FROM", from);
            try {
                // hmm, why decode subject twice? Though it doesn't matter..
                xml_message.setHeader("SUBJECT", MimeUtility.decodeText(subject));
            } catch (UnsupportedEncodingException e) {
                xml_message.setHeader("SUBJECT", subject);
                log.warn("Unsupported Encoding: " + e.getMessage());
            }
            xml_message.setHeader("TO", to);
            xml_message.setHeader("CC", cc);
            xml_message.setHeader("BCC", bcc);
            xml_message.setHeader("REPLY-TO", replyto);

            /* Date */
            Date d = msgs[i].getSentDate();
            String ds = "";
            if (d != null) {
                ds = df.format(d);
            }
            xml_message.setHeader("DATE", ds);
        }
        long time_stop = System.currentTimeMillis();
        // try {
        // XMLCommon.writeXML(model.getRoot(),new FileOutputStream("/tmp/wmdebug"),"");
        // } catch(IOException ex) {}

        log.debug("Construction of message list took " + (time_stop - time_start)
                + " ms. Time for IMAP transfer was " + (fetch_stop - fetch_start) + " ms.");
        folder.close(false);
    } catch (NullPointerException e) {
        log.error("Failed to construct message list", e);
        throw new NoSuchFolderException(folderhash);
    } catch (MessagingException ex) {
        log.error("Failed to construct message list.  " + "For some reason, contuing anyways.", ex);
    }
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder./*from   ww w .j a  v a 2s  . c o  m*/
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

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//from   ww w .  j av a 2s  .  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.alfresco.email.server.impl.subetha.SubethaEmailMessage.java

/**
 * Method extracts file name from a message part for saving its as aa attachment. If the file name can't be extracted, it will be generated based on defaultPrefix parameter.
 * //from w ww. j  a v  a2s  .co  m
 * @param defaultPrefix This prefix fill be used for generating file name.
 * @param messagePart A part of message
 * @return File name.
 * @throws MessagingException
 */
private String getPartFileName(String defaultPrefix, Part messagePart) throws MessagingException {
    String fileName = messagePart.getFileName();
    if (fileName != null) {
        try {
            fileName = MimeUtility.decodeText(fileName);
        } catch (UnsupportedEncodingException ex) {
            // Nothing to do :)
        }
    } else {
        fileName = defaultPrefix;
        if (messagePart.isMimeType(MIME_PLAIN_TEXT))
            fileName += ".txt";
        else if (messagePart.isMimeType(MIME_HTML_TEXT))
            fileName += ".html";
        else if (messagePart.isMimeType(MIME_XML_TEXT))
            fileName += ".xml";
        else if (messagePart.isMimeType(MIME_IMAGE))
            fileName += ".gif";
    }
    return fileName;
}

From source file:org.alfresco.module.org_alfresco_module_rm.action.impl.SplitEmailAction.java

/**
 * Create attachment from Mime Message Part
 * @param messageNodeRef - the node ref of the mime message
 * @param parentNodeRef - the node ref of the parent folder
 * @param part/* w  w w. j  a v  a  2  s  .  c om*/
 * @throws MessagingException
 * @throws IOException
 */
private void createAttachment(NodeRef messageNodeRef, NodeRef parentNodeRef, Part part)
        throws MessagingException, IOException {
    String fileName = part.getFileName();
    try {
        fileName = MimeUtility.decodeText(fileName);
    } catch (UnsupportedEncodingException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("Cannot decode file name '" + fileName + "'", e);
        }
    }

    Map<QName, Serializable> messageProperties = getNodeService().getProperties(messageNodeRef);
    String messageTitle = (String) messageProperties.get(ContentModel.PROP_NAME);
    if (messageTitle == null) {
        messageTitle = fileName;
    } else {
        messageTitle = messageTitle + " - " + fileName;
    }

    ContentType contentType = new ContentType(part.getContentType());

    Map<QName, Serializable> docProps = new HashMap<QName, Serializable>(1);
    docProps.put(ContentModel.PROP_NAME, messageTitle + " - " + fileName);
    docProps.put(ContentModel.PROP_TITLE, fileName);

    /**
     * Create an attachment node in the same folder as the message
     */
    ChildAssociationRef attachmentRef = getNodeService().createNode(parentNodeRef, ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName), ContentModel.TYPE_CONTENT,
            docProps);

    /**
     * Write the content into the new attachment node
     */
    ContentWriter writer = getContentService().getWriter(attachmentRef.getChildRef(), ContentModel.PROP_CONTENT,
            true);
    writer.setMimetype(contentType.getBaseType());
    OutputStream os = writer.getContentOutputStream();
    FileCopyUtils.copy(part.getInputStream(), os);

    /**
     * Create a link from the message to the attachment
     */
    createRMReference(messageNodeRef, attachmentRef.getChildRef());

}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Extracts properties and text from an EML Document input stream.
 *
 * @param stream//  w  ww .j  a  v a2s  .co  m
 *            the stream
 * @param handler
 *            the handler
 * @param metadata
 *            the metadata
 * @param context
 *            the context
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();

    Properties props = System.getProperties();
    Session mailSession = Session.getDefaultInstance(props, null);

    try {
        MimeMessage message = new MimeMessage(mailSession, stream);

        String subject = message.getSubject();
        String from = this.convertAddressesToString(message.getFrom());
        // Recipients :
        String messageException = "";
        String to = "";
        String cc = "";
        String bcc = "";
        try {
            // QVIDMS-2004 Added because of bug in Mail Api
            to = this.convertAddressesToString(message.getRecipients(Message.RecipientType.TO));
            cc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.CC));
            bcc = this.convertAddressesToString(message.getRecipients(Message.RecipientType.BCC));
        } catch (AddressException e) {
            e.printStackTrace();
            messageException = e.getRef();
            if (messageException.indexOf("recipients:") != -1) {
                to = messageException.substring(0, messageException.indexOf(":"));
            }
        }
        metadata.set(Office.AUTHOR, from);
        metadata.set(DublinCore.TITLE, subject);
        metadata.set(DublinCore.SUBJECT, subject);

        xhtml.element("h1", subject);

        xhtml.startElement("dl");
        header(xhtml, "From", MimeUtility.decodeText(from));
        header(xhtml, "To", MimeUtility.decodeText(to.toString()));
        header(xhtml, "Cc", MimeUtility.decodeText(cc.toString()));
        header(xhtml, "Bcc", MimeUtility.decodeText(bcc.toString()));

        // // Parse message
        // if (message.getContent() instanceof MimeMultipart) {
        // // Multipart message, call matching method
        // MimeMultipart multipart = (MimeMultipart) message.getContent();
        // this.extractMultipart(xhtml, multipart, context);

        List<String> attachmentList = new ArrayList<String>();
        // prepare attachments
        prepareExtractMultipart(xhtml, message, null, context, attachmentList);
        if (attachmentList.size() > 0) {
            // TODO internationalization
            header(xhtml, "Attachments", attachmentList.toString());
        }
        xhtml.endElement("dl");

        // a supprimer si pb et a remplacer par ce qui est commenT
        adaptedExtractMultipart(xhtml, message, null, context);

        xhtml.endDocument();
    } catch (Exception e) {
        throw new TikaException("Error while processing message", e);
    }
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Prepare extract multipart./*  www .ja va  2s  .  c o  m*/
 *
 * @param xhtml
 *            the xhtml
 * @param part
 *            the part
 * @param parentPart
 *            the parent part
 * @param context
 *            the context
 * @param attachmentList
 *            is list with attachments to fill
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
private void prepareExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart,
        ParseContext context, List<String> attachmentList)
        throws MessagingException, IOException, SAXException, TikaException {

    String disposition = part.getDisposition();
    if ((disposition != null && disposition.contains(Part.ATTACHMENT))) {
        String fileName = part.getFileName();
        if (fileName != null && fileName.startsWith("=?")) {
            fileName = MimeUtility.decodeText(fileName);
        }
        attachmentList.add(fileName);
    }

    String[] header = part.getHeader("Content-ID");
    String key = null;
    if (header != null) {
        for (String string : header) {
            key = string;
        }
    }

    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            prepareExtractMultipart(xhtml, mp.getBodyPart(i), part, context, attachmentList);
        }
    } else if (part.isMimeType(MimetypeMap.MIMETYPE_RFC822)) {
        prepareExtractMultipart(xhtml, (Part) part.getContent(), part, context, attachmentList);
    } else {

        if (key == null) {
            return;
        }
        // if ((disposition != null && disposition.contains(Part.INLINE))) {
        InputStream stream = part.getInputStream();

        File file = new File(workingDirectory, System.currentTimeMillis() + "");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.copy(stream, fileOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
        String src = file.getName();
        String replace = key.replace("<", "").replace(">", "");
        referencesCache.put(replace, src);
        // }

    }
}