Example usage for javax.mail Message getFrom

List of usage examples for javax.mail Message getFrom

Introduction

In this page you can find the example usage for javax.mail Message getFrom.

Prototype

public abstract Address[] getFrom() throws MessagingException;

Source Link

Document

Returns the "From" attribute.

Usage

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

public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave)
        throws Exception {
    MimeMessage msg = null;/*from   ww  w .  j av a 2  s .co  m*/
    boolean success = true;

    String[] to = SimpleMessage.breakAddr(smsg.getTo());
    String[] cc = SimpleMessage.breakAddr(smsg.getCc());
    String[] bcc = SimpleMessage.breakAddr(smsg.getBcc());
    String replyTo = smsg.getReplyTo();

    msg = new MimeMessage(mainAccount.getMailSession());
    msg.setFrom(getInternetAddress(from));
    InternetAddress ia = null;

    //set the TO recipient
    for (int q = 0; q < to.length; q++) {
        //        Service.logger.debug("to["+q+"]="+to[q]);
        to[q] = to[q].replace(',', ' ');
        try {
            ia = getInternetAddress(to[q]);
        } catch (AddressException exc) {
            throw new AddressException(to[q]);
        }
        msg.addRecipient(Message.RecipientType.TO, ia);
    }

    //set the CC recipient
    for (int q = 0; q < cc.length; q++) {
        cc[q] = cc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(cc[q]);
        } catch (AddressException exc) {
            throw new AddressException(cc[q]);
        }
        msg.addRecipient(Message.RecipientType.CC, ia);
    }

    //set BCC recipients
    for (int q = 0; q < bcc.length; q++) {
        bcc[q] = bcc[q].replace(',', ' ');
        try {
            ia = getInternetAddress(bcc[q]);
        } catch (AddressException exc) {
            throw new AddressException(bcc[q]);
        }
        msg.addRecipient(Message.RecipientType.BCC, ia);
    }

    //set reply to addr
    if (replyTo != null && replyTo.length() > 0) {
        Address[] replyaddr = new Address[1];
        replyaddr[0] = getInternetAddress(replyTo);
        msg.setReplyTo(replyaddr);
    }

    //add any header
    String headerLines[] = smsg.getHeaderLines();
    for (int i = 0; i < headerLines.length; ++i) {
        if (!headerLines[i].startsWith("Sonicle-reply-folder")) {
            msg.addHeaderLine(headerLines[i]);
        }
    }

    //add reply/references
    String inreplyto = smsg.getInReplyTo();
    String references[] = smsg.getReferences();
    String replyfolder = smsg.getReplyFolder();
    if (inreplyto != null) {
        msg.setHeader("In-Reply-To", inreplyto);
    }
    if (references != null && references[0] != null) {
        msg.setHeader("References", references[0]);
    }
    if (tosave) {
        if (replyfolder != null) {
            msg.setHeader("Sonicle-reply-folder", replyfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }

    //add forward data
    String forwardedfrom = smsg.getForwardedFrom();
    String forwardedfolder = smsg.getForwardedFolder();
    if (forwardedfrom != null) {
        msg.setHeader("Forwarded-From", forwardedfrom);
    }
    if (tosave) {
        if (forwardedfolder != null) {
            msg.setHeader("Sonicle-forwarded-folder", forwardedfolder);
        }
        msg.setHeader("Sonicle-draft", "true");
    }
    //set the subject
    String subject = smsg.getSubject();
    try {
        //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null);
        subject = MimeUtility.encodeText(smsg.getSubject());
    } catch (Exception exc) {
    }
    msg.setSubject(subject);

    //set priority
    int priority = smsg.getPriority();
    if (priority != 3) {
        msg.setHeader("X-Priority", "" + priority);

        //set receipt
    }
    String receiptTo = from;
    try {
        receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null);
    } catch (Exception exc) {
    }
    if (smsg.getReceipt()) {
        msg.setHeader("Disposition-Notification-To", from);

        //see if there are any new attachments for the message
    }
    int noAttach;
    int newAttach;

    if (attachments == null) {
        newAttach = 0;
    } else {
        newAttach = attachments.size();
    }

    //get the array of the old attachments
    Part[] oldParts = smsg.getAttachments();

    //check if there are old attachments
    if (oldParts == null) {
        noAttach = 0;
    } else { //old attachments exist
        noAttach = oldParts.length;
    }

    if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) {
        // create the main Multipart
        MimeMultipart mp = new MimeMultipart("mixed");
        MimeMultipart unrelated = null;

        String textcontent = smsg.getTextContent();
        //if is text, or no alternative text is available, add the content as one single body part
        //else create a multipart/alternative with both rich and text mime content
        if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) {
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            mp.addBodyPart(mbp1);
        } else {
            MimeMultipart alternative = new MimeMultipart("alternative");
            //the rich part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8"));
            //the text part
            MimeBodyPart mbp1 = new MimeBodyPart();

            /*          ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length());
             com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos);
             for(int i=0;i<textcontent.length();++i) {
             try {
             qpe.write(textcontent.charAt(i));
             } catch(IOException exc) {
             Service.logger.error("Exception",exc);
             }
             }
             textcontent=new String(bos.toByteArray());*/
            mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8"));
            //          mbp1.setHeader("Content-transfer-encoding","quoted-printable");

            alternative.addBodyPart(mbp1);
            alternative.addBodyPart(mbp2);

            MimeBodyPart altbody = new MimeBodyPart();
            altbody.setContent(alternative);

            mp.addBodyPart(altbody);
        }

        if (noAttach > 0) { //if there are old attachments
            // create the parts with the attachments
            //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach];
            //Part[] mbps2 = new Part[noAttach];

            //for(int e = 0;e < noAttach;e++) {
            //  mbps2[e] = (Part)oldParts[e];
            //}//end for e
            //add the old attachment parts
            for (int r = 0; r < noAttach; r++) {
                Object content = null;
                String contentType = null;
                String contentFileName = null;
                if (oldParts[r] instanceof Message) {
                    //                Service.logger.debug("Attachment is a message");
                    Message msgpart = (Message) oldParts[r];
                    MimeMessage mm = new MimeMessage(mainAccount.getMailSession());
                    mm.addFrom(msgpart.getFrom());
                    mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO));
                    mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC));
                    mm.setRecipients(Message.RecipientType.BCC,
                            msgpart.getRecipients(Message.RecipientType.BCC));
                    mm.setReplyTo(msgpart.getReplyTo());
                    mm.setSentDate(msgpart.getSentDate());
                    mm.setSubject(msgpart.getSubject());
                    mm.setContent(msgpart.getContent(), msgpart.getContentType());
                    content = mm;
                    contentType = "message/rfc822";
                } else {
                    //                Service.logger.debug("Attachment is not a message");
                    content = oldParts[r].getContent();
                    if (!(content instanceof MimeMultipart)) {
                        contentType = oldParts[r].getContentType();
                        contentFileName = oldParts[r].getFileName();
                    }
                }
                MimeBodyPart mbp = new MimeBodyPart();
                if (contentFileName != null) {
                    mbp.setFileName(contentFileName);
                    //              Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName);
                    contentType += "; name=\"" + contentFileName + "\"";
                }
                if (content instanceof MimeMultipart)
                    mbp.setContent((MimeMultipart) content);
                else
                    mbp.setDataHandler(new DataHandler(content, contentType));
                mp.addBodyPart(mbp);
            }

        } //end if, adding old attachments

        if (newAttach > 0) { //if there are new attachments
            // create the parts with the attachments
            MimeBodyPart[] mbps = new MimeBodyPart[newAttach];

            for (int e = 0; e < newAttach; e++) {
                mbps[e] = new MimeBodyPart();

                // attach the file to the message
                JsAttachment attach = (JsAttachment) attachments.get(e);
                UploadedFile upfile = getUploadedFile(attach.uploadId);
                FileDataSource fds = new FileDataSource(upfile.getFile());
                mbps[e].setDataHandler(new DataHandler(fds));
                // filename starts has format:
                // "_" + userid + sessionId + "_" + filename
                //
                if (attach.inline) {
                    mbps[e].setDisposition(Part.INLINE);
                }
                String contentFileName = attach.fileName.trim();
                mbps[e].setFileName(contentFileName);
                String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\"";
                mbps[e].setHeader("Content-type", contentType);
                if (attach.cid != null && attach.cid.trim().length() > 0) {
                    mbps[e].setHeader("Content-ID", "<" + attach.cid + ">");
                    mbps[e].setHeader("X-Attachment-Id", attach.cid);
                    mbps[e].setDisposition(Part.INLINE);
                    if (unrelated == null)
                        unrelated = new MimeMultipart("mixed");
                }
            } //end for e

            //add the new attachment parts
            if (unrelated == null) {
                for (int r = 0; r < newAttach; r++)
                    mp.addBodyPart(mbps[r]);
            } else {
                //mp becomes the related part with text parts and cids
                MimeMultipart related = mp;
                related.setSubType("related");
                //nest the related part into the mixed part
                mp = unrelated;
                MimeBodyPart mbd = new MimeBodyPart();
                mbd.setContent(related);
                mp.addBodyPart(mbd);
                for (int r = 0; r < newAttach; r++) {
                    if (mbps[r].getHeader("Content-ID") != null) {
                        related.addBodyPart(mbps[r]);
                    } else {
                        mp.addBodyPart(mbps[r]);
                    }
                }
            }

        } //end if, adding new attachments

        //
        //          msg.addHeaderLine("This is a multi-part message in MIME format.");
        // add the Multipart to the message
        msg.setContent(mp);

    } else { //end if newattach
        msg.setText(smsg.getContent());
    } //singlepart message

    msg.setSentDate(new java.util.Date());

    return msg;

}

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

private String getForwardBody(Message msg, String body, int format, boolean isHtml, String fromtitle,
        String totitle, String cctitle, String datetitle, String subjecttitle) throws MessagingException {
    UserProfile profile = environment.getProfile();
    Locale locale = profile.getLocale();
    String msgSubject = msg.getSubject();
    if (msgSubject == null) {
        msgSubject = "";
    }//from w ww  .  ja v  a2  s. c  o m
    msgSubject = MailUtils.htmlescape(msgSubject);
    Address ad[] = msg.getFrom();
    String msgFrom = "";
    if (ad != null) {
        msgFrom = isHtml ? getHTMLDecodedAddress(ad[0]) : getDecodedAddress(ad[0]);
    }
    java.util.Date dt = msg.getSentDate();
    String msgDate = "";
    if (dt != null) {
        msgDate = DateFormat.getDateTimeInstance(java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale)
                .format(dt);
    }
    ad = msg.getRecipients(Message.RecipientType.TO);
    String msgTo = null;
    if (ad != null) {
        msgTo = "";
        for (int j = 0; j < ad.length; ++j) {
            msgTo += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " ";
        }
    }
    ad = msg.getRecipients(Message.RecipientType.CC);
    String msgCc = null;
    if (ad != null) {
        msgCc = "";
        for (int j = 0; j < ad.length; ++j) {
            msgCc += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " ";
        }
    }

    StringBuffer sb = new StringBuffer();
    String cr = "\n";
    if (format != SimpleMessage.FORMAT_TEXT) {
        cr = "<BR>";
    }
    if (format != SimpleMessage.FORMAT_HTML) {
        if (format == SimpleMessage.FORMAT_PREFORMATTED) {
            sb.append("<TT>");
        }
        sb.append(cr + cr + cr
                + "----------------------------------------------------------------------------------" + cr
                + cr);
        sb.append(fromtitle + ": " + msgFrom + cr);
        if (msgTo != null) {
            sb.append(totitle + ": " + msgTo + cr);
        }
        if (msgCc != null) {
            sb.append(cctitle + ": " + msgCc + cr);
        }
        sb.append(datetitle + ": " + msgDate + cr);
        sb.append(subjecttitle + ": " + msgSubject + cr + cr);
        if (format == SimpleMessage.FORMAT_PREFORMATTED) {
            sb.append("</TT>");
        }
    } else {
        sb.append(cr + "<HR>" + cr + cr);
        sb.append("<font face='Arial, Helvetica, sans-serif' size=2>");
        sb.append("<B>" + fromtitle + ":</B> " + msgFrom + "<BR>");
        if (msgTo != null) {
            sb.append("<B>" + totitle + ":</B> " + msgTo + "<BR>");
        }
        if (msgCc != null) {
            sb.append("<B>" + cctitle + ":</B> " + msgCc + "<BR>");
        }
        sb.append("<B>" + datetitle + ":</B> " + msgDate + "<BR>");
        sb.append("<B>" + subjecttitle + ":</B> " + msgSubject + "<BR>");
        sb.append("</font><br>" + cr);
    }

    // Prepend "> " for each line in the body
    //
    if (body != null) {
        if (format == SimpleMessage.FORMAT_HTML) {
            //        sb.append("<TABLE border=0 width='100%'><TR><td width=2 bgcolor=#000088></td><td width=2></td><td>");
            //        sb.append("<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>");
        }
        if (!isHtml) {
            if (format == SimpleMessage.FORMAT_PREFORMATTED) {
                //          sb.append("<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>");
                sb.append("<tt>");
            }
            StringTokenizer st = new StringTokenizer(body, "\n", true);
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                if (token.equals("\n")) {
                    sb.append(cr);
                } else {
                    if (format == SimpleMessage.FORMAT_TEXT) {
                        sb.append("> ");
                    }
                    //sb.append(MailUtils.htmlescape(token));
                    sb.append(token);
                }
            }
            if (format == SimpleMessage.FORMAT_PREFORMATTED) {
                sb.append("</tt>");
                //          sb.append("</BLOCKQUOTE>");
            }
        } else {
            //sb.append(getBodyInnerHtml(body));
            sb.append(body);
        }
        if (format == SimpleMessage.FORMAT_HTML) {
            //        sb.append("</td></tr></table>");
            //        sb.append("</BLOCKQUOTE>");
        }
    }
    return sb.toString();
}

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

private String getReplyBody(Message msg, String body, int format, boolean isHtml, String fromtitle,
        String totitle, String cctitle, String datetitle, String subjecttitle, ArrayList<String> attnames)
        throws MessagingException {
    UserProfile profile = environment.getProfile();
    Locale locale = profile.getLocale();
    String msgSubject = msg.getSubject();
    if (msgSubject == null) {
        msgSubject = "";
    }/*from w  ww.  j  a  va  2  s .  c o  m*/
    msgSubject = MailUtils.htmlescape(msgSubject);
    Address ad[] = msg.getFrom();
    String msgFrom = "";
    if (ad != null) {
        msgFrom = isHtml ? getHTMLDecodedAddress(ad[0]) : getDecodedAddress(ad[0]);
    }
    java.util.Date dt = msg.getSentDate();
    String msgDate = "";
    if (dt != null) {
        msgDate = DateFormat.getDateTimeInstance(java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale)
                .format(dt);
    }
    ad = msg.getRecipients(Message.RecipientType.TO);
    String msgTo = null;
    if (ad != null) {
        msgTo = "";
        for (int j = 0; j < ad.length; ++j) {
            msgTo += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " ";
        }
    }
    ad = msg.getRecipients(Message.RecipientType.CC);
    String msgCc = null;
    if (ad != null) {
        msgCc = "";
        for (int j = 0; j < ad.length; ++j) {
            msgCc += isHtml ? getHTMLDecodedAddress(ad[j]) : getDecodedAddress(ad[j]) + " ";
        }
    }

    //
    /*String sfrom = "";
    try {
       if (msg.getFrom() != null) {
    InternetAddress ia = (InternetAddress) msg.getFrom()[0];
    String personal = ia.getPersonal();
    String mail = ia.getAddress();
    if (personal == null || personal.equals(mail)) {
       sfrom = mail;
    } else {
       sfrom = personal + " <" + mail + ">";
    }
       }
    } catch (Exception exc) {
               
    }*/
    StringBuffer sb = new StringBuffer();
    String cr = "\n";
    if (format != SimpleMessage.FORMAT_TEXT) {
        cr = "<BR>";
    }
    if (format != SimpleMessage.FORMAT_HTML) {
        if (format == SimpleMessage.FORMAT_PREFORMATTED) {
            sb.append("<TT>");
        }
        sb.append(cr + cr + cr
                + "----------------------------------------------------------------------------------" + cr
                + cr);
        sb.append(fromtitle + ": " + msgFrom + cr);
        if (msgTo != null) {
            sb.append(totitle + ": " + msgTo + cr);
        }
        if (msgCc != null) {
            sb.append(cctitle + ": " + msgCc + cr);
        }
        sb.append(datetitle + ": " + msgDate + cr);
        sb.append(subjecttitle + ": " + msgSubject + cr + cr);
        if (format == SimpleMessage.FORMAT_PREFORMATTED) {
            sb.append("</TT>");
        }
    } else {
        sb.append(cr + "<HR>" + cr + cr);
        sb.append("<font face='Arial, Helvetica, sans-serif' size=2>");
        sb.append("<B>" + fromtitle + ":</B> " + msgFrom + "<BR>");
        if (msgTo != null) {
            sb.append("<B>" + totitle + ":</B> " + msgTo + "<BR>");
        }
        if (msgCc != null) {
            sb.append("<B>" + cctitle + ":</B> " + msgCc + "<BR>");
        }
        sb.append("<B>" + datetitle + ":</B> " + msgDate + "<BR>");
        sb.append("<B>" + subjecttitle + ":</B> " + msgSubject + "<BR>");
        sb.append("</font><br>" + cr);
    }

    // Prepend "> " for each line in the body
    //
    if (body != null) {
        if (format == SimpleMessage.FORMAT_HTML) {
            //        sb.append("<TABLE border=0 width='100%'><TR><td width=2 bgcolor=#000088></td><td width=2></td><td>");
            sb.append(
                    "<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>");
        }
        if (!isHtml) {
            if (format == SimpleMessage.FORMAT_PREFORMATTED) {
                sb.append(
                        "<BLOCKQUOTE style='BORDER-LEFT: #000080 2px solid; MARGIN-LEFT: 5px; PADDING-LEFT: 5px'>");
                sb.append("<tt>");
            }
            StringTokenizer st = new StringTokenizer(body, "\n", true);
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                if (token.equals("\n")) {
                    sb.append(cr);
                } else {
                    if (format == SimpleMessage.FORMAT_TEXT) {
                        sb.append("> ");
                    }
                    //sb.append(MailUtils.htmlescape(token));
                    sb.append(token);
                }
            }
            if (format == SimpleMessage.FORMAT_PREFORMATTED) {
                sb.append("</tt>");
                sb.append("</BLOCKQUOTE>");
            }
        } else {
            /*
            //String ubody = body.toUpperCase();
            while (true) {
               int ix1 = StringUtils.indexOfIgnoreCase(body,"<BODY");
               if (ix1 < 0) {
                  break;
               }
               int ix2 = StringUtils.indexOfIgnoreCase(body,">", ix1 + 1);
               if (ix2 < 0) {
                  ix2 = ix1 + 4;
               }
               int ix3 = StringUtils.indexOfIgnoreCase(body,"</BODY", ix2 + 1);
               if (ix3 > 0) {
                  body = body.substring(ix2 + 1, ix3);
               } else {
                  body = body.substring(ix2 + 1);
               }
            }
            //body=removeStartEndTag(body,unwantedTags);
            */

            sb.append(body);
        }
        htmlAppendAttachmentNames(sb, attnames);
        if (format == SimpleMessage.FORMAT_HTML) {
            //        sb.append("</td></tr></table>");
            sb.append("</BLOCKQUOTE>");
        }
    }
    return sb.toString();
}

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

public void dmsArchiveMessages(FolderCache from, long nuids[], String idcategory, String idsubcategory,
        boolean fullthreads) throws MessagingException, FileNotFoundException, IOException {
    UserProfile profile = environment.getProfile();
    String archiveto = ss.getDmsArchivePath();
    for (long nuid : nuids) {
        Message msg = from.getMessage(nuid);

        String id = getMessageID(msg);
        if (id.startsWith("<")) {
            id = id.substring(1, id.length() - 1);
        }//w  w w. j av a  2s.c  om
        id = id.replaceAll("\\\\", "_");
        id = id.replaceAll("/", "_");
        String filename = archiveto + "/" + id + ".eml";
        String txtname = archiveto + "/" + id + ".txt";
        File file = new File(filename);
        File txtfile = new File(txtname);
        //Only if spool file does not exists
        if (!file.exists()) {

            String emailfrom = "nomail@nodomain.it";
            Address a[] = msg.getFrom();
            if (a != null && a.length > 0) {
                InternetAddress sender = ((InternetAddress) a[0]);
                emailfrom = sender.getAddress();
            }
            String emailto = "nomail@nodomain.it";
            a = msg.getRecipients(Message.RecipientType.TO);
            if (a != null && a.length > 0) {
                InternetAddress to = ((InternetAddress) a[0]);
                emailto = to.getAddress();
            }
            String subject = msg.getSubject();
            java.util.Date date = msg.getReceivedDate();
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTime(date);
            int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
            int mm = cal.get(java.util.Calendar.MONTH) + 1;
            int yyyy = cal.get(java.util.Calendar.YEAR);
            String sdd = dd < 10 ? "0" + dd : "" + dd;
            String smm = mm < 10 ? "0" + mm : "" + mm;
            String syyyy = "" + yyyy;

            FileOutputStream fos = new FileOutputStream(file);
            msg.writeTo(fos);
            fos.close();

            PrintWriter pw = new PrintWriter(txtfile);
            pw.println(emailfrom);
            pw.println(emailto);
            pw.println(subject);
            pw.println(sdd + "/" + smm + "/" + syyyy);
            pw.println(profile.getUserId());
            pw.println(idcategory);
            pw.println(idsubcategory);
            pw.close();
        }
    }
    from.markDmsArchivedMessages(nuids, fullthreads);
}

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());
    }//w  ww .  j  av  a2 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);
    }
}