Example usage for javax.mail Part getDisposition

List of usage examples for javax.mail Part getDisposition

Introduction

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

Prototype

public String getDisposition() throws MessagingException;

Source Link

Document

Return the disposition of this part.

Usage

From source file:org.nuclos.server.ruleengine.RuleInterface.java

/**
 *
 * @param pop3Host/*w  ww. ja  va 2s.c  om*/
 * @param pop3Port
 * @param pop3User
 * @param pop3Password
 * @param remove
 * @return
 * @throws NuclosFatalRuleException
 */
public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User,
        final String pop3Password, boolean remove) throws NuclosFatalRuleException {
    try {
        Properties properties = new Properties();
        properties.setProperty("mail.pop3.host", pop3Host);
        properties.setProperty("mail.pop3.port", pop3Port);
        properties.setProperty("mail.pop3.auth", "true");
        properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(pop3User, pop3Password);
            }
        });

        session.setDebug(true);
        Store store = session.getStore("pop3");
        store.connect();

        Folder folder = store.getFolder("INBOX");
        if (remove) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        List<NuclosMail> result = new ArrayList<NuclosMail>();

        Message message[] = folder.getMessages();
        for (int i = 0; i < message.length; i++) {
            Message m = message[i];
            NuclosMail mail = new NuclosMail();
            logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: "
                    + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType()
                    + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate());

            Address[] senders = m.getFrom();
            if (senders.length == 1 && senders[0] instanceof InternetAddress) {
                mail.setFrom(((InternetAddress) senders[0]).getAddress());
            } else {
                mail.setFrom(Arrays.toString(m.getFrom()));
            }
            mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO)));
            mail.setSubject(m.getSubject());

            if (m.isMimeType("text/plain")) {
                mail.setMessage((String) m.getContent());
            } else {
                Multipart mp = (Multipart) m.getContent();
                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);
                    String disposition = part.getDisposition();
                    MimeBodyPart mimePart = (MimeBodyPart) part;
                    logger.debug(
                            "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType());

                    if (disposition == null
                            && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) {
                        mail.setMessage((String) mimePart.getDataHandler().getContent());
                    }
                }
                getAttachments(mp, mail);
            }

            result.add(mail);

            if (remove) {
                m.setFlag(Flags.Flag.DELETED, true);
            }
        }

        if (remove) {
            folder.close(true);
        } else {
            folder.close(false);
        }

        store.close();

        return result;
    } catch (Exception e) {
        throw new NuclosFatalRuleException(e);
    }
}

From source file:org.sakaiproject.james.SakaiMailet.java

/**
 * Breaks email messages into parts which can be saved as files (saves as attachments) or viewed as plain text (added to body of message).
 * //from  w w w . ja v a2s  . c o m
 * @param siteId
 *        Site associated with attachments, if any
 * @param p
 *        The message-part embedded in a message..
 * @param id
 *        The string containing the message's id.
 * @param bodyBuf
 *        The string-buffers in which the plain/text and/or html/text message body is being built.
 * @param bodyContentType
 *        The value of the Content-Type header for the mesage body.
 * @param attachments
 *        The ReferenceVector in which references to attachments are collected.
 * @param embedCount
 *        An Integer that counts embedded messages (outer message is zero).
 * @return Value of embedCount (updated if this call processed any embedded messages).
 */
protected Integer parseParts(String siteId, Part p, String id, StringBuilder bodyBuf[],
        StringBuilder bodyContentType, List attachments, Integer embedCount)
        throws MessagingException, IOException {
    // increment embedded message counter
    if (p instanceof Message) {
        embedCount = Integer.valueOf(embedCount.intValue() + 1);
    }

    String type = p.getContentType();

    // discard if content-type is unknown
    if (type == null || "".equals(type)) {
        M_log.warn(this + " message with unknown content-type discarded");
    }

    // add plain text to bodyBuf[0]
    else if (p.isMimeType("text/plain") && p.getFileName() == null) {
        Object o = null;
        // let them convert to text if possible
        // but if bad encaps get the stream and do it ourselves
        try {
            o = p.getContent();
        } catch (java.io.UnsupportedEncodingException ignore) {
            o = p.getInputStream();
        }

        String txt = null;
        String innerContentType = p.getContentType();

        if (o instanceof String) {
            txt = (String) p.getContent();
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        else if (o instanceof InputStream) {
            InputStream in = (InputStream) o;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[in.available()];
            for (int len = in.read(buf); len != -1; len = in.read(buf))
                out.write(buf, 0, len);
            String charset = (new ContentType(innerContentType)).getParameter("charset");
            // RFC 2045 says if no char set specified use US-ASCII.
            // If specified but illegal that's less clear. The common case is X-UNKNOWN.
            // my sense is that UTF-8 is most likely these days but the sample we got
            // was actually ISO 8859-1. Could also justify using US-ASCII. Duh...
            if (charset == null)
                charset = "us-ascii";
            try {
                txt = out.toString(MimeUtility.javaCharset(charset));
            } catch (java.io.UnsupportedEncodingException ignore) {
                txt = out.toString("UTF-8");
            }
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        // remove extra line breaks added by mac Mail, perhaps others
        // characterized by a space followed by a line break
        if (txt != null) {
            txt = txt.replaceAll(" \n", " ");
        }

        // make sure previous message parts ended with newline
        if (bodyBuf[0].length() > 0 && bodyBuf[0].charAt(bodyBuf[0].length() - 1) != '\n')
            bodyBuf[0].append("\n");

        bodyBuf[0].append(txt);
    }

    // add html text to bodyBuf[1]
    else if (p.isMimeType("text/html") && p.getFileName() == null) {
        Object o = null;
        // let them convert to text if possible
        // but if bad encaps get the stream and do it ourselves
        try {
            o = p.getContent();
        } catch (java.io.UnsupportedEncodingException ignore) {
            o = p.getInputStream();
        }
        String txt = null;
        String innerContentType = p.getContentType();

        if (o instanceof String) {
            txt = (String) p.getContent();
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        else if (o instanceof InputStream) {
            InputStream in = (InputStream) o;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[in.available()];
            for (int len = in.read(buf); len != -1; len = in.read(buf))
                out.write(buf, 0, len);
            String charset = (new ContentType(innerContentType)).getParameter("charset");
            if (charset == null)
                charset = "us-ascii";
            try {
                txt = out.toString(MimeUtility.javaCharset(charset));
            } catch (java.io.UnsupportedEncodingException ignore) {
                txt = out.toString("UTF-8");
            }
            if (bodyContentType != null && bodyContentType.length() == 0)
                bodyContentType.append(innerContentType);
        }

        // remove bad image tags and naughty javascript
        if (txt != null) {
            txt = Web.cleanHtml(txt);
        }

        bodyBuf[1].append(txt);
    }

    // process subparts of multiparts
    else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            embedCount = parseParts(siteId, mp.getBodyPart(i), id, bodyBuf, bodyContentType, attachments,
                    embedCount);
        }
    }

    // Discard parts with mime-type application/applefile. If an e-mail message contains an attachment is sent from
    // a macintosh, you may get two parts, one for the data fork and one for the resource fork. The part that
    // corresponds to the resource fork confuses users, this has mime-type application/applefile. The best thing
    // is to discard it.
    else if (p.isMimeType("application/applefile")) {
        M_log.warn(this + " message with application/applefile discarded");
    }

    // discard enriched text version of the message.
    // Sakai only uses the plain/text or html/text version of the message.
    else if (p.isMimeType("text/enriched") && p.getFileName() == null) {
        M_log.warn(this + " message with text/enriched discarded");
    }

    // everything else gets treated as an attachment
    else {
        String name = p.getFileName();

        // look for filenames not parsed by getFileName() 
        if (name == null && type.indexOf(NAME_PREFIX) != -1) {
            name = type.substring(type.indexOf(NAME_PREFIX) + NAME_PREFIX.length());
        }
        // ContentType can't handle filenames with spaces or UTF8 characters
        if (name != null) {
            String decodedName = MimeUtility.decodeText(name); // first decode RFC 2047
            type = type.replace(name, URLEncoder.encode(decodedName, "UTF-8"));
            name = decodedName;
        }

        ContentType cType = new ContentType(type);
        String disposition = p.getDisposition();
        int approxSize = p.getSize();

        if (name == null) {
            name = "unknown";
            // if file's parent is multipart/alternative,
            // provide a better name for the file
            if (p instanceof BodyPart) {
                Multipart parent = ((BodyPart) p).getParent();
                if (parent != null) {
                    String pType = parent.getContentType();
                    ContentType pcType = new ContentType(pType);
                    if (pcType.getBaseType().equalsIgnoreCase("multipart/alternative")) {
                        name = "message" + embedCount;
                    }
                }
            }
            if (p.isMimeType("text/html")) {
                name += ".html";
            } else if (p.isMimeType("text/richtext")) {
                name += ".rtx";
            } else if (p.isMimeType("text/rtf")) {
                name += ".rtf";
            } else if (p.isMimeType("text/enriched")) {
                name += ".etf";
            } else if (p.isMimeType("text/plain")) {
                name += ".txt";
            } else if (p.isMimeType("text/xml")) {
                name += ".xml";
            } else if (p.isMimeType("message/rfc822")) {
                name += ".txt";
            }
        }

        // read the attachments bytes, and create it as an attachment in content hosting
        byte[] bodyBytes = readBody(approxSize, p.getInputStream());
        if ((bodyBytes != null) && (bodyBytes.length > 0)) {
            // can we ignore the attachment it it's just whitespace chars??
            Reference attachment = createAttachment(siteId, attachments, cType.getBaseType(), name, bodyBytes,
                    id);

            // add plain/text attachment reference (if plain/text message)
            if (attachment != null && bodyBuf[0].length() > 0)
                bodyBuf[0]
                        .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n");

            // add html/text attachment reference (if html/text message)
            if (attachment != null && bodyBuf[1].length() > 0)
                bodyBuf[1].append(
                        "<p>[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]</p>");

            // add plain/text attachment reference (if no plain/text and no html/text)
            if (attachment != null && bodyBuf[0].length() == 0 && bodyBuf[1].length() == 0)
                bodyBuf[0]
                        .append("[see attachment: \"" + name + "\", size: " + bodyBytes.length + " bytes]\n\n");
        }
    }

    return embedCount;
}

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

private boolean appendReplyParts(Part p, StringBuffer htmlsb, StringBuffer textsb, ArrayList<String> attnames)
        throws MessagingException, IOException {
    boolean isHtml = false;
    String disp = p.getDisposition();
    if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT) && !p.isMimeType("message/*")) {
        if (attnames != null) {/*from ww  w . j  a  v  a 2 s  . c o  m*/
            String id[] = p.getHeader("Content-ID");
            if (id == null || id[0] == null) {
                String filename = p.getFileName();
                if (filename != null) {
                    if (filename.startsWith("<")) {
                        filename = filename.substring(1);
                    }
                    if (filename.endsWith(">")) {
                        filename = filename.substring(0, filename.length() - 1);
                    }
                }
                if (filename != null) {
                    attnames.add(filename);
                }
            }
        }
        return false;
    }
    if (p.isMimeType("text/html")) {
        //String htmlcontent=(String)p.getContent();
        String htmlcontent = getTextContentAsString(p);
        textsb.append(MailUtils.htmlToText(MailUtils.htmlunescapesource(htmlcontent)));
        htmlsb.append(MailUtils.htmlescapefixsource(/*getBodyInnerHtml(*/htmlcontent/*)*/));
        isHtml = true;
    } else if (p.isMimeType("text/plain")) {
        String content = getTextContentAsString(p);
        textsb.append(content);
        htmlsb.append(startpre + MailUtils.htmlescape(content) + endpre);
        isHtml = false;
    } else if (p.isMimeType("message/delivery-status") || p.isMimeType("message/disposition-notification")) {
        InputStream is = (InputStream) p.getContent();
        char cbuf[] = new char[8000];
        byte bbuf[] = new byte[8000];
        int n = 0;
        htmlsb.append(startpre);
        while ((n = is.read(bbuf)) >= 0) {
            if (n > 0) {
                for (int i = 0; i < n; ++i) {
                    cbuf[i] = (char) bbuf[i];
                }
                textsb.append(cbuf);
                htmlsb.append(MailUtils.htmlescape(new String(cbuf)));
            }
        }
        htmlsb.append(endpre);
        is.close();
        isHtml = false;
    } else if (p.isMimeType("multipart/alternative")) {
        Multipart mp = (Multipart) p.getContent();
        Part bestPart = null;
        for (int i = 0; i < mp.getCount(); ++i) {
            Part part = mp.getBodyPart(i);
            if (part.isMimeType("multipart/*")) {
                isHtml = appendReplyParts(part, htmlsb, textsb, attnames);
                if (isHtml) {
                    bestPart = null;
                    break;
                }
            } else if (part.isMimeType("text/html")) {
                bestPart = part;
                break;
            } else if (bestPart == null && part.isMimeType("text/plain")) {
                bestPart = part;
            } else if (bestPart == null && part.isMimeType("message/*")) {
                bestPart = part;
            }
        }
        if (bestPart != null) {
            isHtml = appendReplyParts(bestPart, htmlsb, textsb, attnames);
        }
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); ++i) {
            if (appendReplyParts(mp.getBodyPart(i), htmlsb, textsb, attnames)) {
                isHtml = true;
            }
        }
    } else if (p.isMimeType("message/*")) {
        Object content = p.getContent();
        if (appendReplyParts((MimeMessage) content, htmlsb, textsb, attnames)) {
            isHtml = true;
        }
    } else {
    }
    textsb.append('\n');
    textsb.append('\n');

    return isHtml;
}

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

public void processGetEditMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pnewmsgid = request.getParameter("newmsgid");
    long newmsgid = Long.parseLong(pnewmsgid);
    String sout = null;/*from w w w  .  java2 s . c  o  m*/
    try {
        MailEditFormat editFormat = ServletUtils.getEnumParameter(request, "format", null,
                MailEditFormat.class);
        if (editFormat == null)
            editFormat = EnumUtils.forSerializedName(us.getFormat(), MailEditFormat.HTML, MailEditFormat.class);
        boolean isPlainEdit = MailEditFormat.PLAIN_TEXT.equals(editFormat);

        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        IMAPMessage m = (IMAPMessage) mcache.getMessage(Long.parseLong(puidmessage));
        m.setPeek(us.isManualSeen());
        //boolean wasseen = m.isSet(Flags.Flag.SEEN);
        String vheader[] = m.getHeader("Disposition-Notification-To");
        boolean receipt = false;
        int priority = 3;
        boolean recipients = false;
        boolean toDelete = false;
        if (account.isDraftsFolder(pfoldername)) {
            if (vheader != null && vheader[0] != null) {
                receipt = true;
            }
            priority = getPriority(m);
            recipients = true;

            //if autosaved drafts, delete
            String values[] = m.getHeader(HEADER_X_WEBTOP_MSGID);
            if (values != null && values.length > 0) {
                try {
                    long msgId = Long.parseLong(values[0]);
                    if (msgId > 0) {
                        toDelete = true;
                    }
                } catch (NumberFormatException exc) {

                }
            }
        }

        sout = "{\n result: true,";
        String subject = m.getSubject();
        if (subject == null) {
            subject = "";
        }
        sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n";

        String inreplyto = null;
        String references[] = null;
        String vs[] = m.getHeader("In-Reply-To");
        if (vs != null && vs[0] != null) {
            inreplyto = vs[0];
        }
        references = m.getHeader("References");
        if (inreplyto != null) {
            vs = m.getHeader("Sonicle-reply-folder");
            String replyfolder = null;
            if (vs != null && vs[0] != null) {
                replyfolder = vs[0];
            }
            if (replyfolder != null) {
                sout += " replyfolder: '" + StringEscapeUtils.escapeEcmaScript(replyfolder) + "',";
            }
            sout += " inreplyto: '" + StringEscapeUtils.escapeEcmaScript(inreplyto) + "',";
        }
        if (references != null) {
            String refs = "";
            for (String s : references) {
                refs += StringEscapeUtils.escapeEcmaScript(s) + " ";
            }
            sout += " references: '" + refs.trim() + "',";
        }

        String forwardedfrom = null;
        vs = m.getHeader("Forwarded-From");
        if (vs != null && vs[0] != null) {
            forwardedfrom = vs[0];
        }
        if (forwardedfrom != null) {
            vs = m.getHeader("Sonicle-forwarded-folder");
            String forwardedfolder = null;
            if (vs != null && vs[0] != null) {
                forwardedfolder = vs[0];
            }
            if (forwardedfolder != null) {
                sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(forwardedfolder) + "',";
            }
            sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',";
        }

        sout += " receipt: " + receipt + ",\n";
        sout += " priority: " + (priority >= 3 ? false : true) + ",\n";

        Identity ident = null;
        Address from[] = m.getFrom();
        InternetAddress iafrom = null;
        if (from != null && from.length > 0) {
            iafrom = (InternetAddress) from[0];
            String email = iafrom.getAddress();
            String displayname = iafrom.getPersonal();
            if (displayname == null)
                displayname = email;
            //sout+=" from: { email: '"+StringEscapeUtils.escapeEcmaScript(email)+"', displayname: '"+StringEscapeUtils.escapeEcmaScript(displayname)+"' },\n";
            ident = mprofile.getIdentity(displayname, email);
        }

        sout += " recipients: [\n";
        if (recipients) {
            Address tos[] = m.getRecipients(RecipientType.TO);
            String srec = "";
            if (tos != null) {
                for (Address to : tos) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'to', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(to)) + "'" + " }";
                }
            }
            Address ccs[] = m.getRecipients(RecipientType.CC);
            if (ccs != null) {
                for (Address cc : ccs) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'cc', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(cc)) + "'" + " }";
                }
            }
            Address bccs[] = m.getRecipients(RecipientType.BCC);
            if (bccs != null) {
                for (Address bcc : bccs) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'bcc', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(bcc)) + "'" + " }";
                }
            }

            sout += srec;
        } else {
            sout += "   { " + "rtype: 'to', " + "email: ''" + " }";

        }
        sout += " ],\n";

        String html = "";
        boolean balanceTags = isPreviewBalanceTags(iafrom);
        ArrayList<String> htmlparts = mcache.getHTMLParts((MimeMessage) m, newmsgid, true, balanceTags);
        for (String xhtml : htmlparts) {
            html += xhtml + "<BR><BR>";
        }
        HTMLMailData maildata = mcache.getMailData((MimeMessage) m);
        //if(!wasseen){
        //   if (us.isManualSeen()) {
        //      m.setFlag(Flags.Flag.SEEN, false);
        //   }
        //}

        boolean first = true;
        sout += " attachments: [\n";
        for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) {
            Part part = maildata.getAttachmentPart(i);
            String filename = getPartName(part);

            String cids[] = part.getHeader("Content-ID");
            String cid = null;
            //String cid=filename;
            if (cids != null && cids[0] != null) {
                cid = cids[0];
                if (cid.startsWith("<"))
                    cid = cid.substring(1);
                if (cid.endsWith(">"))
                    cid = cid.substring(0, cid.length() - 1);
            }

            if (filename == null) {
                filename = cid;
            }
            String mime = part.getContentType();
            UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, mime, part.getInputStream());
            boolean inline = false;
            if (part.getDisposition() != null) {
                inline = part.getDisposition().equalsIgnoreCase(Part.INLINE);
            }
            if (!first) {
                sout += ",\n";
            }
            sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', "
                    + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: "
                    + (cid == null ? null : "'" + StringEscapeUtils.escapeEcmaScript(cid) + "'") + ", "
                    + " inline: " + inline + ", " + " fileSize: " + upfile.getSize() + " " + " }";
            first = false;
            //TODO: change this weird matching of cids2urls!
            html = StringUtils.replace(html, "cid:" + cid,
                    "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID
                            + "&action=PreviewAttachment&nowriter=true&uploadId=" + upfile.getUploadId()
                            + "&cid=" + cid);

        }
        sout += "\n ],\n";

        if (ident != null)
            sout += " identityId: " + ident.getIdentityId() + ",\n";
        sout += " origuid:" + puidmessage + ",\n";
        sout += " deleted:" + toDelete + ",\n";
        sout += " folder:'" + pfoldername + "',\n";
        sout += " content:'" + (isPlainEdit
                ? StringEscapeUtils.escapeEcmaScript(MailUtils.htmlToText(MailUtils.htmlunescapesource(html)))
                : StringEscapeUtils.escapeEcmaScript(html)) + "',\n";
        sout += " format:'" + EnumUtils.toSerializedName(editFormat) + "'\n";
        sout += "\n}";

        m.setPeek(false);

        if (toDelete) {
            m.setFlag(Flags.Flag.DELETED, true);
            m.getFolder().expunge();
        }

        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
    }
}

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

public void processGetForwardMessage(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {/*from  ww  w.  j  ava2  s. c om*/
    MailAccount account = getAccount(request);
    UserProfile profile = environment.getProfile();
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pnewmsgid = request.getParameter("newmsgid");
    String pattached = request.getParameter("attached");
    boolean attached = (pattached != null && pattached.equals("1"));
    long newmsgid = Long.parseLong(pnewmsgid);
    String sout = null;
    try {
        String format = us.getFormat();
        boolean isHtml = format.equals("html");
        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        Message m = mcache.getMessage(Long.parseLong(puidmessage));
        if (m.isExpunged()) {
            throw new MessagingException("Message " + puidmessage + " expunged");
        }
        SimpleMessage smsg = getForwardMsg(newmsgid, m, isHtml, lookupResource(MailLocaleKey.MSG_FROMTITLE),
                lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE),
                lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE),
                attached);

        sout = "{\n result: true,";
        Identity ident = mprofile.getIdentity(pfoldername);
        String forwardedfrom = smsg.getForwardedFrom();
        sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',";
        if (forwardedfrom != null) {
            sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',";
        }
        String subject = smsg.getSubject();
        sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n";

        String html = smsg.getContent();
        String text = smsg.getTextContent();
        if (!attached) {
            HTMLMailData maildata = mcache.getMailData((MimeMessage) m);
            boolean first = true;
            sout += " attachments: [\n";

            for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) {
                try {
                    Part part = maildata.getAttachmentPart(i);
                    String filename = getPartName(part);
                    if (!part.isMimeType("message/*")) {
                        String cids[] = part.getHeader("Content-ID");
                        String cid = null;
                        //String cid=filename;
                        if (cids != null && cids[0] != null) {
                            cid = cids[0];
                            if (cid.startsWith("<"))
                                cid = cid.substring(1);
                            if (cid.endsWith(">"))
                                cid = cid.substring(0, cid.length() - 1);
                        }

                        if (filename == null)
                            filename = cid;
                        String mime = MailUtils.getMediaTypeFromHeader(part.getContentType());
                        UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, mime,
                                part.getInputStream());
                        boolean inline = false;
                        if (part.getDisposition() != null) {
                            inline = part.getDisposition().equalsIgnoreCase(Part.INLINE);
                        }
                        if (!first) {
                            sout += ",\n";
                        }
                        sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId())
                                + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', "
                                + " cid: "
                                + (cid == null ? null : "'" + StringEscapeUtils.escapeEcmaScript(cid) + "'")
                                + ", " + " inline: " + inline + ", " + " fileSize: " + upfile.getSize() + ", "
                                + " editable: " + isFileEditableInDocEditor(filename) + " " + " }";
                        first = false;
                        //TODO: change this weird matching of cids2urls!
                        html = StringUtils.replace(html, "cid:" + cid,
                                "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID
                                        + "&action=PreviewAttachment&nowriter=true&uploadId="
                                        + upfile.getUploadId() + "&cid=" + cid);
                    }
                } catch (Exception exc) {
                    Service.logger.error("Exception", exc);
                }
            }

            sout += "\n ],\n";
            //String surl = "service-request?service="+SERVICE_ID+"&action=PreviewAttachment&nowriter=true&newmsgid=" + newmsgid + "&cid=";
            //html = replaceCidUrls(html, maildata, surl);
        } else {
            String filename = m.getSubject() + ".eml";
            UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, "message/rfc822",
                    ((IMAPMessage) m).getMimeStream());
            sout += " attachments: [\n";
            sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', "
                    + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: null, "
                    + " inline: false, " + " fileSize: " + upfile.getSize() + ", " + " editable: "
                    + isFileEditableInDocEditor(filename) + " " + " }";
            sout += "\n ],\n";
        }
        sout += " identityId: " + ident.getIdentityId() + ",\n";
        sout += " origuid:" + puidmessage + ",\n";
        if (isHtml) {
            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n";
        } else {
            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n";
        }
        sout += " format:'" + format + "'\n";
        sout += "\n}";
        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
        out.println(sout);
    }
}

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

public void processGetMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pidattach = request.getParameter("idattach");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");
    String nopec = request.getParameter("nopec");
    int idattach = 0;
    boolean isEditor = request.getParameter("editor") != null;
    boolean setSeen = ServletUtils.getBooleanParameter(request, "setseen", true);

    if (df == null) {
        df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM,
                environment.getProfile().getLocale());
    }//from  w  w w  . java 2  s. co  m
    try {
        FolderCache mcache = null;
        Message m = null;
        IMAPMessage im = null;
        int recs = 0;
        long msguid = -1;
        String vheader[] = null;
        boolean wasseen = false;
        boolean isPECView = false;
        String sout = "{\nmessage: [\n";
        if (providername == null) {
            account.checkStoreConnected();
            mcache = account.getFolderCache(pfoldername);
            msguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(msguid);
            im = (IMAPMessage) m;
            im.setPeek(us.isManualSeen());
            if (m.isExpunged())
                throw new MessagingException("Message " + puidmessage + " expunged");
            vheader = m.getHeader("Disposition-Notification-To");
            wasseen = m.isSet(Flags.Flag.SEEN);
            if (pidattach != null) {

                HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
                Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
                m = (Message) part.getContent();
                idattach = Integer.parseInt(pidattach) + 1;
            } else if (nopec == null && mcache.isPEC()) {
                String hdrs[] = m.getHeader(HDR_PEC_TRASPORTO);
                if (hdrs != null && hdrs.length > 0 && hdrs[0].equals("posta-certificata")) {
                    HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
                    int parts = mailData.getAttachmentPartCount();
                    for (int i = 0; i < parts; ++i) {
                        Part p = mailData.getAttachmentPart(i);
                        if (p.isMimeType("message/rfc822")) {
                            m = (Message) p.getContent();
                            idattach = i + 1;
                            isPECView = true;
                            break;
                        }
                    }
                }
            }
        } else {
            // TODO: provider get message!!!!
            /*                WebTopService provider=wts.getServiceByName(providername);
                         MessageContentProvider mcp=provider.getMessageContentProvider(providerid);
                         m=new MimeMessage(session,mcp.getSource());
                         mcache=fcProvided;
                         mcache.addProvidedMessage(providername, providerid, m);*/
        }
        String messageid = getMessageID(m);
        String subject = m.getSubject();
        if (subject == null) {
            subject = "";
        } else {
            try {
                subject = MailUtils.decodeQString(subject);
            } catch (Exception exc) {

            }
        }
        java.util.Date d = m.getSentDate();
        if (d == null) {
            d = m.getReceivedDate();
        }
        if (d == null) {
            d = new java.util.Date(0);
        }
        String date = df.format(d).replaceAll("\\.", ":");
        String fromName = "";
        String fromEmail = "";
        Address as[] = m.getFrom();
        InternetAddress iafrom = null;
        if (as != null && as.length > 0) {
            iafrom = (InternetAddress) as[0];
            fromName = iafrom.getPersonal();
            fromEmail = adjustEmail(iafrom.getAddress());
            if (fromName == null) {
                fromName = fromEmail;
            }
        }
        sout += "{iddata:'from',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromName))
                + "',value2:'" + StringEscapeUtils.escapeEcmaScript(fromEmail) + "',value3:0},\n";
        recs += 2;
        Address tos[] = m.getRecipients(RecipientType.TO);
        if (tos != null) {
            for (Address to : tos) {
                InternetAddress ia = (InternetAddress) to;
                String toName = ia.getPersonal();
                String toEmail = adjustEmail(ia.getAddress());
                if (toName == null) {
                    toName = toEmail;
                }
                sout += "{iddata:'to',value1:'"
                        + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toName)) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(toEmail) + "',value3:0},\n";
                ++recs;
            }
        }
        Address ccs[] = m.getRecipients(RecipientType.CC);
        if (ccs != null) {
            for (Address cc : ccs) {
                InternetAddress ia = (InternetAddress) cc;
                String ccName = ia.getPersonal();
                String ccEmail = adjustEmail(ia.getAddress());
                if (ccName == null) {
                    ccName = ccEmail;
                }
                sout += "{iddata:'cc',value1:'" + StringEscapeUtils.escapeEcmaScript(ccName) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(ccEmail) + "',value3:0},\n";
                ++recs;
            }
        }
        Address bccs[] = m.getRecipients(RecipientType.BCC);
        if (bccs != null)
            for (Address bcc : bccs) {
                InternetAddress ia = (InternetAddress) bcc;
                String bccName = ia.getPersonal();
                String bccEmail = adjustEmail(ia.getAddress());
                if (bccName == null) {
                    bccName = bccEmail;
                }
                sout += "{iddata:'bcc',value1:'" + StringEscapeUtils.escapeEcmaScript(bccName) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(bccEmail) + "',value3:0},\n";
                ++recs;
            }
        ArrayList<String> htmlparts = null;
        boolean balanceTags = isPreviewBalanceTags(iafrom);
        if (providername == null) {
            htmlparts = mcache.getHTMLParts((MimeMessage) m, msguid, false, balanceTags);
        } else {
            htmlparts = mcache.getHTMLParts((MimeMessage) m, providername, providerid, balanceTags);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        ICalendarRequest ir = mailData.getICalRequest();
        if (ir != null) {
            if (htmlparts.size() > 0)
                sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(htmlparts.get(0))
                        + "',value2:'',value3:0},\n";
        } else {
            for (String html : htmlparts) {
                //sout += "{iddata:'html',value1:'" + OldUtils.jsEscape(html) + "',value2:'',value3:0},\n";
                sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(html)
                        + "',value2:'',value3:0},\n";
                ++recs;
            }
        }

        /*if (!wasseen) {
           //if (us.isManualSeen()) {
           if (!setSeen) {
              m.setFlag(Flags.Flag.SEEN, false);
           } else {
              //if no html part, flag seen is not set
              if (htmlparts.size()==0) m.setFlag(Flags.Flag.SEEN, true);
           }
        }*/
        if (!us.isManualSeen()) {
            if (htmlparts.size() == 0)
                m.setFlag(Flags.Flag.SEEN, true);
        } else {
            if (setSeen)
                m.setFlag(Flags.Flag.SEEN, true);
        }

        int acount = mailData.getAttachmentPartCount();
        for (int i = 0; i < acount; ++i) {
            Part p = mailData.getAttachmentPart(i);
            String ctype = p.getContentType();
            Service.logger.debug("attachment " + i + " is " + ctype);
            int ix = ctype.indexOf(';');
            if (ix > 0) {
                ctype = ctype.substring(0, ix);
            }
            String cidnames[] = p.getHeader("Content-ID");
            String cidname = null;
            if (cidnames != null && cidnames.length > 0)
                cidname = mcache.normalizeCidFileName(cidnames[0]);
            boolean isInlineable = isInlineableMime(ctype);
            boolean inline = ((p.getHeader("Content-Location") != null) || (cidname != null)) && isInlineable;
            if (inline && cidname != null)
                inline = mailData.isReferencedCid(cidname);
            if (p.getDisposition() != null && p.getDisposition().equalsIgnoreCase(Part.INLINE) && inline) {
                continue;
            }

            String imgname = null;
            boolean isCalendar = ctype.equalsIgnoreCase("text/calendar")
                    || ctype.equalsIgnoreCase("text/icalendar");
            if (isCalendar) {
                imgname = "resources/" + getManifest().getId() + "/laf/" + cus.getLookAndFeel()
                        + "/ical_16.png";
            }

            String pname = getPartName(p);
            try {
                pname = MailUtils.decodeQString(pname);
            } catch (Exception exc) {
            }
            if (pname == null) {
                ix = ctype.indexOf("/");
                String fname = ctype;
                if (ix > 0) {
                    fname = ctype.substring(ix + 1);
                }
                //String ext = WT.getMediaTypeExtension(ctype);
                //if (ext == null) {
                pname = fname;
                //} else {
                //   pname = fname + "." + ext;
                //}
                if (isCalendar)
                    pname += ".ics";
            } else {
                if (isCalendar && !StringUtils.endsWithIgnoreCase(pname, ".ics"))
                    pname += ".ics";
            }
            int size = p.getSize();
            int lines = (size / 76);
            int rsize = size - (lines * 2);//(p.getSize()/4)*3;
            String iddata = ctype.equalsIgnoreCase("message/rfc822") ? "eml"
                    : (inline ? "inlineattach" : "attach");
            boolean editable = isFileEditableInDocEditor(pname);

            sout += "{iddata:'" + iddata + "',value1:'" + (i + idattach) + "',value2:'"
                    + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(pname)) + "',value3:" + rsize
                    + ",value4:"
                    + (imgname == null ? "null" : "'" + StringEscapeUtils.escapeEcmaScript(imgname) + "'")
                    + ", editable: " + editable + " },\n";
        }
        if (!mcache.isDrafts() && !mcache.isSent() && !mcache.isSpam() && !mcache.isTrash()
                && !mcache.isArchive()) {
            if (vheader != null && vheader[0] != null && !wasseen) {
                sout += "{iddata:'receipt',value1:'" + us.getReadReceiptConfirmation() + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(vheader[0]) + "',value3:0},\n";
            }
        }

        String h = getSingleHeaderValue(m, "Sonicle-send-scheduled");
        if (h != null && h.equals("true")) {
            java.util.Calendar scal = parseScheduleHeader(getSingleHeaderValue(m, "Sonicle-send-date"),
                    getSingleHeaderValue(m, "Sonicle-send-time"));
            if (scal != null) {
                java.util.Date sd = scal.getTime();
                String sdate = df.format(sd).replaceAll("\\.", ":");
                sout += "{iddata:'scheddate',value1:'" + StringEscapeUtils.escapeEcmaScript(sdate)
                        + "',value2:'',value3:0},\n";
            }
        }

        if (ir != null) {

            /*
            ICalendarManager calMgr = (ICalendarManager)WT.getServiceManager("com.sonicle.webtop.calendar",environment.getProfileId());
            if (calMgr != null) {
               if (ir.getMethod().equals("REPLY")) {
                  calMgr.updateEventFromICalReply(ir.getCalendar());
                  //TODO: gestire lato client una notifica di avvenuto aggiornamento
               } else {
                  Event evt = calMgr..getEvent(GetEventScope.PERSONAL_AND_INCOMING, false, ir.getUID())
                  if (evt != null) {
             UserProfileId pid = getEnv().getProfileId();
             UserProfile.Data ud = WT.getUserData(pid);
             boolean iAmOrganizer = StringUtils.equalsIgnoreCase(evt.getOrganizerAddress(), ud.getEmailAddress());
             boolean iAmOwner = pid.equals(calMgr.getCalendarOwner(evt.getCalendarId()));
                     
             if (!iAmOrganizer && !iAmOwner) {
                //TODO: gestire lato client l'aggiornamento: Accetta/Rifiuta, Aggiorna e20 dopo update/request
             }
                  }
               }
            }
            */

            ICalendarManager cm = (ICalendarManager) WT.getServiceManager("com.sonicle.webtop.calendar", true,
                    environment.getProfileId());
            if (cm != null) {
                int eid = -1;
                //Event ev=cm.getEventByScope(EventScope.PERSONAL_AND_INCOMING, ir.getUID());
                Event ev = null;
                if (ir.getMethod().equals("REPLY")) {
                    // Previous impl. forced (forceOriginal == true)
                    ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID());
                } else {
                    ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID());
                }

                UserProfileId pid = getEnv().getProfileId();
                UserProfile.Data ud = WT.getUserData(pid);

                if (ev != null) {
                    InternetAddress organizer = InternetAddressUtils.toInternetAddress(ev.getOrganizer());
                    boolean iAmOwner = pid.equals(cm.getCalendarOwner(ev.getCalendarId()));
                    boolean iAmOrganizer = (organizer != null)
                            && StringUtils.equalsIgnoreCase(organizer.getAddress(), ud.getEmailAddress());

                    //TODO: in reply controllo se mail combacia con quella dell'attendee che risponde...
                    //TODO: rimuovere controllo su data? dovrebbe sempre aggiornare?

                    if (iAmOwner || iAmOrganizer) {
                        eid = 0;
                        //TODO: troviamo un modo per capire se la risposta si riverisce all'ultima versione dell'evento? Nuovo campo timestamp?
                        /*
                        DateTime dtEvt = ev.getRevisionTimestamp().withMillisOfSecond(0).withZone(DateTimeZone.UTC);
                        DateTime dtICal = ICal4jUtils.fromICal4jDate(ir.getLastModified(), ICal4jUtils.getTimeZone(DateTimeZone.UTC));
                        if (dtICal.isAfter(dtEvt)) {
                           eid = 0;
                        } else {
                           eid = ev.getEventId();
                        }
                        */
                    }
                }
                sout += "{iddata:'ical',value1:'" + ir.getMethod() + "',value2:'" + ir.getUID() + "',value3:'"
                        + eid + "'},\n";
            }
        }

        sout += "{iddata:'date',value1:'" + StringEscapeUtils.escapeEcmaScript(date)
                + "',value2:'',value3:0},\n";
        sout += "{iddata:'subject',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject))
                + "',value2:'',value3:0},\n";
        sout += "{iddata:'messageid',value1:'" + StringEscapeUtils.escapeEcmaScript(messageid)
                + "',value2:'',value3:0}\n";

        if (providername == null && !mcache.isSpecial()) {
            mcache.refreshUnreads();
        }
        long millis = System.currentTimeMillis();
        sout += "\n],\n";

        String svtags = getJSTagsArray(m.getFlags());
        if (svtags != null)
            sout += "tags: " + svtags + ",\n";

        if (isPECView) {
            sout += "pec: true,\n";
        }

        sout += "total:" + recs + ",\nmillis:" + millis + "\n}\n";
        out.println(sout);

        if (im != null)
            im.setPeek(false);

        //            if (!wasopen) folder.close(false);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}