Example usage for javax.mail Folder close

List of usage examples for javax.mail Folder close

Introduction

In this page you can find the example usage for javax.mail Folder close.

Prototype

public abstract void close(boolean expunge) throws MessagingException;

Source Link

Document

Close this Folder.

Usage

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * The main method of this job. Called by confluence every time the mail2news trigger
 * fires.// w w w .  j av  a  2 s.  co m
 *
 * @see com.atlassian.quartz.jobs.AbstractJob#doExecute(org.quartz.JobExecutionContext)
 */
public void doExecute(JobExecutionContext arg0) throws JobExecutionException {

    /* The mailstore object used to connect to the server */
    Store store = null;

    try {

        this.log.info("Executing mail2news plugin.");

        /* check if we have all necessary components */
        if (pageManager == null) {
            throw new Exception("Null PageManager instance.");
        }
        if (spaceManager == null) {
            throw new Exception("Null SpaceManager instance.");
        }
        if (configurationManager == null) {
            throw new Exception("Null ConfigurationManager instance.");
        }

        /* get the mail configuration from the manager */
        MailConfiguration config = configurationManager.getMailConfiguration();
        if (config == null) {
            throw new Exception("Null MailConfiguration instance.");
        }

        /* create the properties for the session */
        Properties prop = new Properties();

        /* get the protocol to use */
        if (config.getProtocol() == null) {
            throw new Exception("Cannot get protocol.");
        }
        String protocol = config.getProtocol().toLowerCase().concat(config.getSecure() ? "s" : "");
        /* assemble the property prefix for this protocol */
        String propertyPrefix = "mail.";
        propertyPrefix = propertyPrefix.concat(protocol).concat(".");

        /* get the server port from the configuration and add it to the properties,
         * but only if it is actually set. If port = 0 this means we use the standard
         * port for the chosen protocol */
        int port = config.getPort();
        if (port != 0) {
            prop.setProperty(propertyPrefix.concat("port"), "" + port);
        }

        /* set connection timeout (10 seconds) */
        prop.setProperty(propertyPrefix.concat("connectiontimeout"), "10000");

        /* get the session for connecting to the mail server */
        Session session = Session.getInstance(prop, null);

        /* get the mail store, using the desired protocol */
        if (config.getSecure()) {
            store = session.getStore(protocol);
        } else {
            store = session.getStore(protocol);
        }

        /* get the host and credentials for the mail server from the configuration */
        String host = config.getServer();
        String username = config.getUsername();
        String password = config.getPassword();

        /* sanity check */
        if (host == null || username == null || password == null) {
            throw new Exception("Incomplete mail configuration settings (at least one setting is null).");
        }

        /* connect to the mailstore */
        try {
            store.connect(host, username, password);
        } catch (AuthenticationFailedException afe) {
            throw new Exception("Authentication for mail store failed: " + afe.getMessage(), afe);
        } catch (MessagingException me) {
            throw new Exception("Connecting to mail store failed: " + me.getMessage(), me);
        } catch (IllegalStateException ise) {
            throw new Exception("Connecting to mail store failed, already connected: " + ise.getMessage(), ise);
        } catch (Exception e) {
            throw new Exception("Connecting to mail store failed, general exception: " + e.getMessage(), e);
        }

        /***
         * Open the INBOX
         ***/

        /* get the INBOX folder */
        Folder folderInbox = store.getFolder("INBOX");
        /* we need to open it READ_WRITE, because we want to move messages we already handled */
        try {
            folderInbox.open(Folder.READ_WRITE);
        } catch (FolderNotFoundException fnfe) {
            throw new Exception("Could not find INBOX folder: " + fnfe.getMessage(), fnfe);
        } catch (Exception e) {
            throw new Exception("Could not open INBOX folder: " + e.getMessage(), e);
        }

        /* here we have to split, because IMAP will be handled differently from POP3 */
        if (config.getProtocol().toLowerCase().equals("imap")) {
            /***
             * Open the default folder, under which will be the processed
             * and the invalid folder.
             ***/

            Folder folderDefault = null;
            try {
                folderDefault = store.getDefaultFolder();
            } catch (MessagingException me) {
                throw new Exception("Could not get default folder: " + me.getMessage(), me);
            }
            /* sanity check */
            try {
                if (!folderDefault.exists()) {
                    throw new Exception(
                            "Default folder does not exist. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author.");
                }
            } catch (MessagingException me) {
                throw new Exception("Could not test existence of the default folder: " + me.getMessage(), me);
            }

            /**
             * This is kind of a fallback mechanism. For some reasons it can happen that
             * the default folder has an empty name and exists() returns true, but when
             * trying to create a subfolder it generates an error message.
             * So what we do here is if the name of the default folder is empty, we
             * look for the "INBOX" folder, which has to exist and then create the
             * subfolders under this folder.
             */
            if (folderDefault.getName().equals("")) {
                this.log.warn("Default folder has empty name. Looking for 'INBOX' folder as root folder.");
                folderDefault = store.getFolder("INBOX");
                if (!folderDefault.exists()) {
                    throw new Exception(
                            "Could not find default folder and could not find 'INBOX' folder. Cannot continue. This might indicate that this software does not like the given IMAP server. If you think you know what the problem is contact the author.");
                }
            }

            /***
             * Open the folder for processed messages
             ***/

            /* get the folder where we store processed messages */
            Folder folderProcessed = folderDefault.getFolder("Processed");
            /* check if it exists */
            if (!folderProcessed.exists()) {
                /* does not exist, create it */
                try {
                    if (!folderProcessed.create(Folder.HOLDS_MESSAGES)) {
                        throw new Exception("Creating 'processed' folder failed.");
                    }
                } catch (MessagingException me) {
                    throw new Exception("Could not create 'processed' folder: " + me.getMessage(), me);
                }
            }
            /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */
            try {
                folderProcessed.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException fnfe) {
                throw new Exception("Could not find 'processed' folder: " + fnfe.getMessage(), fnfe);
            } catch (Exception e) {
                throw new Exception("Could not open 'processed' folder: " + e.getMessage(), e);
            }

            /***
             * Open the folder for invalid messages
             ***/

            /* get the folder where we store invalid messages */
            Folder folderInvalid = folderDefault.getFolder("Invalid");
            /* check if it exists */
            if (!folderInvalid.exists()) {
                /* does not exist, create it */
                try {
                    if (!folderInvalid.create(Folder.HOLDS_MESSAGES)) {
                        throw new Exception("Creating 'invalid' folder failed.");
                    }
                } catch (MessagingException me) {
                    throw new Exception("Could not create 'invalid' folder: " + me.getMessage(), me);
                }
            }
            /* we need to open it READ_WRITE, because we want to move messages we already handled to this folder */
            try {
                folderInvalid.open(Folder.READ_WRITE);
            } catch (FolderNotFoundException fnfe) {
                throw new Exception("Could not find 'invalid' folder: " + fnfe.getMessage(), fnfe);
            } catch (Exception e) {
                throw new Exception("Could not open 'invalid' folder: " + e.getMessage(), e);
            }

            /***
             * Get all new messages
             ***/

            /* get all messages in the INBOX */
            Message message[] = folderInbox.getMessages();

            /* go through all messages and get the unseen ones (all should be unseen,
             * as the seen ones get moved to a different folder
             */
            for (int i = 0; i < message.length; i++) {

                if (message[i].isSet(Flags.Flag.SEEN)) {
                    /* this message has been seen, should not happen */
                    /* send email to the sender */
                    sendErrorMessage(message[i],
                            "This message has already been flagged as seen before being handled and was thus ignored.");
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                Space space = null;
                try {
                    space = getSpaceFromAddress(message[i]);
                } catch (Exception e) {
                    this.log.error("Could not get space from message: " + e.getMessage());
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                /* initialise content and attachments */
                blogEntryContent = null;
                attachments = new LinkedList();
                attachmentsInputStreams = new LinkedList();

                containsImage = false;

                /* get the content of this message */
                try {
                    Object content = message[i].getContent();
                    if (content instanceof Multipart) {
                        handleMultipart((Multipart) content);
                    } else {
                        handlePart(message[i]);
                    }
                } catch (Exception e) {
                    this.log.error("Error while getting content of message: " + e.getMessage(), e);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                try {
                    createBlogPost(space, message[i]);
                } catch (MessagingException me) {
                    this.log.error("Error while creating blog post: " + me.getMessage(), me);
                    /* send email to sender */
                    sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage());
                    /* move this message to the invalid folder */
                    moveMessage(message[i], folderInbox, folderInvalid);
                    /* skip this message */
                    continue;
                }

                /* move the message to the processed folder */
                moveMessage(message[i], folderInbox, folderProcessed);

            }

            /* close the folders, expunging deleted messages in the process */
            folderInbox.close(true);
            folderProcessed.close(true);
            folderInvalid.close(true);
            /* close the store */
            store.close();

        } else if (config.getProtocol().toLowerCase().equals("pop3")) {
            /* get all messages in this POP3 account */
            Message message[] = folderInbox.getMessages();

            /* go through all messages */
            for (int i = 0; i < message.length; i++) {

                Space space = null;
                try {
                    space = getSpaceFromAddress(message[i]);
                } catch (Exception e) {
                    this.log.error("Could not get space from message: " + e.getMessage());
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Could not get space from message: " + e.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                /* initialise content and attachments */
                blogEntryContent = null;
                attachments = new LinkedList();
                attachmentsInputStreams = new LinkedList();

                containsImage = false;

                /* get the content of this message */
                try {
                    Object content = message[i].getContent();
                    if (content instanceof Multipart) {
                        handleMultipart((Multipart) content);
                    } else {
                        handlePart(message[i]);
                    }
                } catch (Exception e) {
                    this.log.error("Error while getting content of message: " + e.getMessage(), e);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while getting content of message: " + e.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                try {
                    createBlogPost(space, message[i]);
                } catch (MessagingException me) {
                    this.log.error("Error while creating blog post: " + me.getMessage(), me);
                    /* send email to the sender */
                    sendErrorMessage(message[i], "Error while creating blog post: " + me.getMessage());
                    /* delete this message */
                    message[i].setFlag(Flags.Flag.DELETED, true);
                    /* get the next message, this message will be deleted when
                     * closing the folder */
                    continue;
                }

                /* finished processing this message, delete it */
                message[i].setFlag(Flags.Flag.DELETED, true);
                /* get the next message, this message will be deleted when
                 * closing the folder */

            }

            /* close the pop3 folder, deleting all messages flagged as DELETED */
            folderInbox.close(true);
            /* close the mail store */
            store.close();

        } else {
            throw new Exception("Unknown protocol: " + config.getProtocol());
        }

    } catch (Exception e) {
        /* catch any exception which was not handled so far */
        this.log.error("Error while executing mail2news job: " + e.getMessage(), e);
        JobExecutionException jee = new JobExecutionException(
                "Error while executing mail2news job: " + e.getMessage(), e, false);
        throw jee;
    } finally {
        /* try to do some cleanup */
        try {
            store.close();
        } catch (Exception e) {
        }
    }
}

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

public void processListMessages(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    CoreManager core = WT.getCoreManager();
    UserProfile profile = environment.getProfile();
    Locale locale = profile.getLocale();
    java.util.Calendar cal = java.util.Calendar.getInstance(locale);
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    //String psortfield = request.getParameter("sort");
    //String psortdir = request.getParameter("dir");
    String pstart = request.getParameter("start");
    String plimit = request.getParameter("limit");
    String ppage = request.getParameter("page");
    String prefresh = request.getParameter("refresh");
    String ptimestamp = request.getParameter("timestamp");
    String pthreaded = request.getParameter("threaded");
    String pthreadaction = request.getParameter("threadaction");
    String pthreadactionuid = request.getParameter("threadactionuid");

    QueryObj queryObj = null;//from   ww w  . j  a v a  2 s .c o  m
    SearchTerm searchTerm = null;
    try {
        queryObj = ServletUtils.getObjectParameter(request, "query", new QueryObj(), QueryObj.class);
    }

    catch (ParameterException parameterException) {
        logger.error("Exception getting query obejct parameter", parameterException);
    }

    boolean refresh = (prefresh != null && prefresh.equals("true"));
    //boolean threaded=(pthreaded!=null && pthreaded.equals("1"));

    //String threadedSetting="list-threaded-"+pfoldername;
    //if (pthreaded==null || pthreaded.equals("2")) {
    //   threaded=us.isMessageListThreaded(pfoldername);
    //} else {
    //   us.setMessageListThreaded(pfoldername, threaded);
    //}
    //System.out.println("timestamp="+ptimestamp);
    long timestamp = Long.parseLong(ptimestamp);

    if (account.isSpecialFolder(pfoldername) || account.isSharedFolder(pfoldername)) {
        logger.debug("folder is special or shared, refresh forced");
        refresh = true;
    }

    String group = us.getMessageListGroup(pfoldername);
    if (group == null) {
        group = "";
    }

    String psortfield = "date";
    String psortdir = "DESC";
    try {
        boolean nogroup = group.equals("");
        JsSort.List sortList = ServletUtils.getObjectParameter(request, "sort", null, JsSort.List.class);
        if (sortList == null) {
            if (nogroup) {
                String s = us.getMessageListSort(pfoldername);
                int ix = s.indexOf("|");
                psortfield = s.substring(0, ix);
                psortdir = s.substring(ix + 1);
            } else {
                psortfield = "date";
                psortdir = "DESC";
            }
        } else {
            JsSort jsSort = sortList.get(0);
            psortfield = jsSort.property;
            psortdir = jsSort.direction;
            if (!nogroup && !psortfield.equals("date")) {
                group = "";
            }
            us.setMessageListGroup(pfoldername, group);
            us.setMessageListSort(pfoldername, psortfield, psortdir);
        }
    } catch (Exception exc) {
        logger.error("Exception", exc);
    }

    SortGroupInfo sgi = getSortGroupInfo(psortfield, psortdir, group);

    //Save search requests

    int start = Integer.parseInt(pstart);
    int limit = Integer.parseInt(plimit);
    int page = 0;
    if (ppage != null) {
        page = Integer.parseInt(ppage);
        start = (page - 1) * limit;
    }
    /*int start = 0;
    int limit = mprofile.getNumMsgList();
    if (ppage==null) {
       if (pstart != null) {
    start = Integer.parseInt(pstart);
       }   
       if (plimit != null) {
    limit = Integer.parseInt(plimit);
       }
    } else {
       int page=Integer.parseInt(ppage);
       int nxpage=mprofile.getNumMsgList();
       start=(page-1)*nxpage;
       limit=nxpage;
    }*/

    String sout = "{\n";
    Folder folder = null;
    boolean connected = false;
    try {
        connected = account.checkStoreConnected();
        if (!connected)
            throw new Exception("Mail account authentication error");

        int funread = 0;
        if (pfoldername == null) {
            folder = account.getDefaultFolder();
        } else {
            folder = account.getFolder(pfoldername);
        }
        boolean issent = account.isSentFolder(folder.getFullName());
        boolean isundersent = account.isUnderSentFolder(folder.getFullName());
        boolean isdrafts = account.isDraftsFolder(folder.getFullName());
        boolean isundershared = account.isUnderSharedFolder(pfoldername);
        if (!issent) {
            String names[] = folder.getFullName().split("\\" + account.getFolderSeparator());
            for (String pname : names) {
                if (account.isSentFolder(pname)) {
                    issent = true;
                    break;
                }
            }
        }

        String ctn = Thread.currentThread().getName();
        String key = folder.getFullName();

        if (!pfoldername.equals("/")) {

            FolderCache mcache = account.getFolderCache(key);
            if (mcache.toBeRefreshed())
                refresh = true;
            //Message msgs[]=mcache.getMessages(ppattern,psearchfield,sortby,ascending,refresh);
            if (psortfield != null && psortdir != null) {
                key += "|" + psortdir + "|" + psortfield;
            }

            searchTerm = ImapQuery.toSearchTerm(this.allFlagStrings, this.atags, queryObj,
                    profile.getTimeZone());

            boolean hasAttachment = queryObj.conditions.stream()
                    .anyMatch(condition -> condition.value.equals("attachment"));
            if (queryObj != null)
                refresh = true;
            MessagesInfo messagesInfo = listMessages(mcache, key, refresh, sgi, timestamp, searchTerm,
                    hasAttachment);
            Message xmsgs[] = messagesInfo.messages;

            if (pthreadaction != null && pthreadaction.trim().length() > 0) {
                long actuid = Long.parseLong(pthreadactionuid);
                mcache.setThreadOpen(actuid, pthreadaction.equals("open"));
            }

            //if threaded, look for the start considering roots and opened children
            if (xmsgs != null && sgi.threaded && page > 1) {
                int i = 0, ni = 0, np = 1;
                long tId = 0;
                while (np < page && ni < xmsgs.length) {
                    SonicleIMAPMessage xm = (SonicleIMAPMessage) xmsgs[ni];
                    ++ni;
                    if (xm.isExpunged())
                        continue;

                    long nuid = mcache.getUID(xm);

                    int tIndent = xm.getThreadIndent();
                    if (tIndent == 0)
                        tId = nuid;
                    else {
                        if (!mcache.isThreadOpen(tId))
                            continue;
                    }

                    ++i;
                    if ((i % limit) == 0)
                        ++np;
                }
                if (np == page) {
                    start = ni;
                    //System.out.println("page "+np+" start is "+start);
                }
            }

            int max = start + limit;
            if (xmsgs != null && max > xmsgs.length)
                max = xmsgs.length;
            ArrayList<Long> autoeditList = new ArrayList<Long>();
            if (xmsgs != null) {
                int total = 0;
                int expunged = 0;

                //calculate expunged
                //for(Message xmsg: xmsgs) {
                //   if (xmsg.isExpunged()) ++expunged;
                //}

                sout += "messages: [\n";

                /*               if (ppattern==null && !isSpecialFolder(mcache.getFolderName())) {
                 //mcache.fetch(msgs,FolderCache.flagsFP,0,start);
                 for(int i=0;i<start;++i) {
                 try {
                 if (!msgs[i].isSet(Flags.Flag.SEEN)) funread++;
                 } catch(Exception exc) {
                        
                 }
                 }
                 }*/
                total = sgi.threaded ? mcache.getThreadedCount() : xmsgs.length;
                if (start < max) {

                    Folder fsent = account.getFolder(account.getFolderSent());
                    boolean openedsent = false;
                    //Fetch others for these messages
                    mcache.fetch(xmsgs, (isdrafts ? draftsFP : messagesInfo.isPEC() ? pecFP : FP), start, max);
                    long tId = 0;
                    for (int i = 0, ni = 0; i < limit; ++ni, ++i) {
                        int ix = start + i;
                        int nx = start + ni;
                        if (nx >= xmsgs.length)
                            break;
                        if (ix >= max)
                            break;

                        SonicleIMAPMessage xm = (SonicleIMAPMessage) xmsgs[nx];
                        if (xm.isExpunged()) {
                            --i;
                            continue;
                        }

                        /*if (messagesInfo.checkSkipPEC(xm)) {
                           --i; --total;
                           continue;
                        }*/

                        /*String ids[]=null;
                         try {
                         ids=xm.getHeader("Message-ID");
                         } catch(MessagingException exc) {
                         --i;
                         continue;
                         }
                         if (ids==null || ids.length==0) { --i; continue; }
                         String idmessage=ids[0];*/

                        long nuid = mcache.getUID(xm);

                        int tIndent = xm.getThreadIndent();
                        if (tIndent == 0)
                            tId = nuid;
                        else if (sgi.threaded) {
                            if (!mcache.isThreadOpen(tId)) {
                                --i;
                                continue;
                            }
                        }
                        boolean tChildren = false;
                        int tUnseenChildren = 0;
                        if (sgi.threaded) {
                            int cnx = nx + 1;
                            while (cnx < xmsgs.length) {
                                SonicleIMAPMessage cxm = (SonicleIMAPMessage) xmsgs[cnx];
                                if (cxm.isExpunged()) {
                                    cnx++;
                                    continue;
                                }
                                while (cxm.getThreadIndent() > 0) {
                                    tChildren = true;
                                    if (!cxm.isExpunged() && !cxm.isSet(Flags.Flag.SEEN))
                                        ++tUnseenChildren;
                                    ++cnx;
                                    if (cnx >= xmsgs.length)
                                        break;
                                    cxm = (SonicleIMAPMessage) xmsgs[cnx];
                                }
                                break;
                            }
                        }

                        Flags flags = xm.getFlags();

                        //Date
                        java.util.Date d = xm.getSentDate();
                        if (d == null)
                            d = xm.getReceivedDate();
                        if (d == null)
                            d = new java.util.Date(0);
                        cal.setTime(d);
                        int yyyy = cal.get(java.util.Calendar.YEAR);
                        int mm = cal.get(java.util.Calendar.MONTH);
                        int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
                        int hhh = cal.get(java.util.Calendar.HOUR_OF_DAY);
                        int mmm = cal.get(java.util.Calendar.MINUTE);
                        int sss = cal.get(java.util.Calendar.SECOND);
                        //From
                        String from = "";
                        String fromemail = "";
                        Address ia[] = xm.getFrom();
                        if (ia != null) {
                            InternetAddress iafrom = (InternetAddress) ia[0];
                            from = iafrom.getPersonal();
                            if (from == null)
                                from = iafrom.getAddress();
                            fromemail = iafrom.getAddress();
                        }
                        from = (from == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(from)));
                        fromemail = (fromemail == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromemail)));

                        //To
                        String to = "";
                        String toemail = "";
                        ia = xm.getRecipients(Message.RecipientType.TO);
                        //if not sent and not shared, show me first if in TO
                        if (ia != null) {
                            InternetAddress iato = (InternetAddress) ia[0];
                            if (!issent && !isundershared) {
                                for (Address ax : ia) {
                                    InternetAddress iax = (InternetAddress) ax;
                                    if (iax.getAddress().equals(profile.getEmailAddress())) {
                                        iato = iax;
                                        break;
                                    }
                                }
                            }
                            to = iato.getPersonal();
                            if (to == null)
                                to = iato.getAddress();
                            toemail = iato.getAddress();
                        }
                        to = (to == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(to)));
                        toemail = (toemail == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toemail)));

                        //Subject
                        String subject = xm.getSubject();
                        if (subject != null) {
                            try {
                                subject = MailUtils.decodeQString(subject);
                            } catch (Exception exc) {

                            }
                        } else
                            subject = "";

                        /*                  if (threaded) {
                                          if (tIndent>0) {
                                             StringBuffer sb=new StringBuffer();
                                             for(int w=0;w<tIndent;++w) sb.append("&nbsp;");
                                             subject=sb+subject;
                                          }
                                       }*/

                        boolean hasAttachments = mcache.hasAttachements(xm);

                        subject = StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject));

                        //Unread
                        boolean unread = !xm.isSet(Flags.Flag.SEEN);
                        if (queryObj != null && unread)
                            ++funread;
                        //Priority
                        int priority = getPriority(xm);
                        //Status
                        java.util.Date today = new java.util.Date();
                        java.util.Calendar cal1 = java.util.Calendar.getInstance(locale);
                        java.util.Calendar cal2 = java.util.Calendar.getInstance(locale);
                        boolean isToday = false;
                        String gdate = "";
                        String sdate = "";
                        String xdate = "";
                        if (d != null) {
                            java.util.Date gd = sgi.threaded ? xm.getMostRecentThreadDate() : d;

                            cal1.setTime(today);
                            cal2.setTime(gd);

                            gdate = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(gd);
                            sdate = cal2.get(java.util.Calendar.YEAR) + "/"
                                    + String.format("%02d", (cal2.get(java.util.Calendar.MONTH) + 1)) + "/"
                                    + String.format("%02d", cal2.get(java.util.Calendar.DATE));
                            //boolean isGdate=group.equals("gdate");
                            if (cal1.get(java.util.Calendar.MONTH) == cal2.get(java.util.Calendar.MONTH)
                                    && cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)) {
                                int dx = cal1.get(java.util.Calendar.DAY_OF_MONTH)
                                        - cal2.get(java.util.Calendar.DAY_OF_MONTH);
                                if (dx == 0) {
                                    isToday = true;
                                    //if (isGdate) {
                                    //   gdate=WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_TODAY)+"  "+gdate;
                                    //}
                                    xdate = WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_TODAY);
                                } else if (dx == 1 /*&& isGdate*/) {
                                    xdate = WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_YESTERDAY);
                                }
                            }
                        }

                        String status = "read";
                        if (flags != null) {
                            if (flags.contains(Flags.Flag.ANSWERED)) {
                                if (flags.contains("$Forwarded"))
                                    status = "repfwd";
                                else
                                    status = "replied";
                            } else if (flags.contains("$Forwarded")) {
                                status = "forwarded";
                            } else if (flags.contains(Flags.Flag.SEEN)) {
                                status = "read";
                            } else if (isToday) {
                                status = "new";
                            } else {
                                status = "unread";
                            }
                            //                    if (flags.contains(Flags.Flag.USER)) flagImage=webtopapp.getUri()+"/images/themes/"+profile.getTheme()+"/mail/flag.gif";
                        }
                        //Size
                        int msgsize = 0;
                        msgsize = (xm.getSize() * 3) / 4;// /1024 + 1;
                        //User flags
                        String cflag = "";
                        for (WebtopFlag webtopFlag : webtopFlags) {
                            String flagstring = webtopFlag.label;
                            //String tbflagstring=webtopFlag.tbLabel;
                            if (!flagstring.equals("complete")) {
                                String oldflagstring = "flag" + flagstring;
                                if (flags.contains(flagstring) || flags.contains(oldflagstring)
                                /*|| (tbflagstring!=null && flags.contains(tbflagstring))*/
                                ) {
                                    cflag = flagstring;
                                }
                            }
                        }
                        boolean flagComplete = flags.contains("complete");
                        if (flagComplete) {
                            if (cflag.length() > 0)
                                cflag += "-complete";
                            else
                                cflag = "complete";
                        }

                        if (cflag.length() == 0 && flags.contains(Flags.Flag.FLAGGED))
                            cflag = "special";

                        boolean hasNote = flags.contains(sflagNote);

                        String svtags = getJSTagsArray(flags);

                        boolean autoedit = false;

                        boolean issched = false;
                        int syyyy = 0;
                        int smm = 0;
                        int sdd = 0;
                        int shhh = 0;
                        int smmm = 0;
                        int ssss = 0;
                        if (isdrafts) {
                            String h = getSingleHeaderValue(xm, "Sonicle-send-scheduled");
                            if (h != null && h.equals("true")) {
                                java.util.Calendar scal = parseScheduleHeader(
                                        getSingleHeaderValue(xm, "Sonicle-send-date"),
                                        getSingleHeaderValue(xm, "Sonicle-send-time"));
                                if (scal != null) {
                                    syyyy = scal.get(java.util.Calendar.YEAR);
                                    smm = scal.get(java.util.Calendar.MONTH);
                                    sdd = scal.get(java.util.Calendar.DAY_OF_MONTH);
                                    shhh = scal.get(java.util.Calendar.HOUR_OF_DAY);
                                    smmm = scal.get(java.util.Calendar.MINUTE);
                                    ssss = scal.get(java.util.Calendar.SECOND);
                                    issched = true;
                                    status = "scheduled";
                                }
                            }

                            h = getSingleHeaderValue(xm, HEADER_SONICLE_FROM_DRAFTER);
                            if (h != null && h.equals("true")) {
                                autoedit = true;
                            }
                        }

                        String xmfoldername = xm.getFolder().getFullName();

                        //idmessage=idmessage.replaceAll("\\\\", "\\\\");
                        //idmessage=Utils.jsEscape(idmessage);
                        if (i > 0)
                            sout += ",\n";
                        boolean archived = false;
                        if (hasDmsDocumentArchiving()) {
                            archived = xm.getHeader("X-WT-Archived") != null;
                            if (!archived) {
                                archived = flags.contains(sflagDmsArchived);
                            }
                        }

                        String msgtext = null;
                        if (us.getShowMessagePreviewOnRow() && isToday && unread) {
                            try {
                                msgtext = MailUtils.peekText(xm);
                                if (msgtext != null) {
                                    msgtext = msgtext.trim();
                                    if (msgtext.length() > 100)
                                        msgtext = msgtext.substring(0, 100);
                                }
                            } catch (MessagingException | IOException ex1) {
                                msgtext = ex1.getMessage();
                            }
                        }

                        String pecstatus = null;
                        if (messagesInfo.isPEC()) {
                            String hdrs[] = xm.getHeader(HDR_PEC_TRASPORTO);
                            if (hdrs != null && hdrs.length > 0
                                    && (hdrs[0].equals("errore") || hdrs[0].equals("posta-certificata")))
                                pecstatus = hdrs[0];
                            else {
                                hdrs = xm.getHeader(HDR_PEC_RICEVUTA);
                                if (hdrs != null && hdrs.length > 0)
                                    pecstatus = hdrs[0];
                            }
                        }

                        sout += "{idmessage:'" + nuid + "'," + "priority:" + priority + "," + "status:'"
                                + status + "'," + "to:'" + to + "'," + "toemail:'" + toemail + "'," + "from:'"
                                + from + "'," + "fromemail:'" + fromemail + "'," + "subject:'" + subject + "',"
                                + (msgtext != null
                                        ? "msgtext: '" + StringEscapeUtils.escapeEcmaScript(msgtext) + "',"
                                        : "")
                                + (sgi.threaded ? "threadId: " + tId + "," : "")
                                + (sgi.threaded ? "threadIndent:" + tIndent + "," : "") + "date: new Date("
                                + yyyy + "," + mm + "," + dd + "," + hhh + "," + mmm + "," + sss + "),"
                                + "gdate: '" + gdate + "'," + "sdate: '" + sdate + "'," + "xdate: '" + xdate
                                + "'," + "unread: " + unread + "," + "size:" + msgsize + ","
                                + (svtags != null ? "tags: " + svtags + "," : "")
                                + (pecstatus != null ? "pecstatus: '" + pecstatus + "'," : "") + "flag:'"
                                + cflag + "'" + (hasNote ? ",note:true" : "") + (archived ? ",arch:true" : "")
                                + (isToday ? ",istoday:true" : "") + (hasAttachments ? ",atts:true" : "")
                                + (issched
                                        ? ",scheddate: new Date(" + syyyy + "," + smm + "," + sdd + "," + shhh
                                                + "," + smmm + "," + ssss + ")"
                                        : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadOpen: " + mcache.isThreadOpen(nuid)
                                        : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadHasChildren: " + tChildren : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadUnseenChildren: " + tUnseenChildren
                                        : "")
                                + (sgi.threaded && xm.hasThreads() && !xm.isMostRecentInThread() ? ",fmtd: true"
                                        : "")
                                + (sgi.threaded && !xmfoldername.equals(folder.getFullName()) ? ",fromfolder: '"
                                        + StringEscapeUtils.escapeEcmaScript(xmfoldername) + "'" : "")
                                + "}";

                        if (autoedit) {
                            autoeditList.add(nuid);
                        }

                        //                sout+="{messageid:'"+m.getMessageID()+"',from:'"+from+"',subject:'"+subject+"',date: new Date("+yyyy+","+mm+","+dd+"),unread: "+unread+"},\n";
                    }

                    if (openedsent)
                        fsent.close(false);
                }
                /*                if (ppattern==null && !isSpecialFolder(mcache.getFolderName())) {
                 //if (max<msgs.length) mcache.fetch(msgs,FolderCache.flagsFP,max,msgs.length);
                 for(int i=max;i<msgs.length;++i) {
                 try {
                 if (!msgs[i].isSet(Flags.Flag.SEEN)) funread++;
                 } catch(Exception exc) {
                        
                 }
                 }
                 } else {
                 funread=mcache.getUnreadMessagesCount();
                 }*/
                if (mcache.isScanForcedOrEnabled()) {
                    //Send message only if first page
                    if (start == 0)
                        mcache.refreshUnreads();
                    funread = mcache.getUnreadMessagesCount();
                } else
                    funread = 0;

                long qlimit = -1;
                long qusage = -1;
                try {
                    Quota quotas[] = account.getQuota("INBOX");
                    if (quotas != null)
                        for (Quota q : quotas) {
                            if ((q.quotaRoot.equals("INBOX") || q.quotaRoot.equals("Quota"))
                                    && q.resources != null) {
                                for (Quota.Resource r : q.resources) {
                                    if (r.name.equals("STORAGE")) {
                                        qlimit = r.limit;
                                        qusage = r.usage;
                                    }
                                }
                            }
                        }
                } catch (MessagingException exc) {
                    logger.debug("Error on QUOTA", exc);
                }

                sout += "\n],\n";
                sout += "total: " + (total - expunged) + ",\n";
                if (qlimit >= 0 && qusage >= 0)
                    sout += "quotaLimit: " + qlimit + ", quotaUsage: " + qusage + ",\n";
                if (messagesInfo.isPEC())
                    sout += "isPEC: true,\n";
                sout += "realTotal: " + (xmsgs.length - expunged) + ",\n";
                sout += "expunged: " + (expunged) + ",\n";
            } else {
                sout += "messages: [],\n" + "total: 0,\n" + "realTotal: 0,\n" + "expunged:0,\n";
            }
            sout += "metaData: {\n" + "  root: 'messages', total: 'total', idProperty: 'idmessage',\n"
                    + "  fields: ['idmessage','priority','status','to','from','subject','date','gdate','unread','size','flag','note','arch','istoday','atts','scheddate','fmtd','fromfolder'],\n"
                    + "  sortInfo: { field: '" + psortfield + "', direction: '" + psortdir + "' },\n"
                    + "  threaded: " + sgi.threaded + ",\n" + "  groupField: '"
                    + (sgi.threaded ? "threadId" : group) + "',\n";

            /*            ColumnVisibilitySetting cvs = us.getColumnVisibilitySetting(pfoldername);
                        ColumnsOrderSetting cos = us.getColumnsOrderSetting();
                        // Apply grid defaults
                        //ColumnVisibilitySetting.applyDefaults(mcache.isSent(), cvs);
                        ColumnVisibilitySetting.applyDefaults(issent||isundersent, cvs);
                    
                        if (autoeditList.size()>0) {
                           sout+="autoedit: [";
                           for(long muid: autoeditList) {
                              sout+=muid+",";
                           }
                           if(StringUtils.right(sout, 1).equals(",")) sout = StringUtils.left(sout, sout.length()-1);
                           sout+="],\n";
                        }
                                
                        // Fills columnsInfo object for client rendering
                        sout += "colsInfo2: [";
                        for (String dataIndex : cvs.keySet()) {
                           sout += "{dataIndex:'" + dataIndex + "',hidden:" + String.valueOf(!cvs.get(dataIndex)) + ",index:"+cos.indexOf(dataIndex)+"},";
                        }
                        if (StringUtils.right(sout, 1).equals(",")) {
                           sout = StringUtils.left(sout, sout.length() - 1);
                        }
                        sout += "]\n";*/

            sout += "},\n";
            sout += "threaded: " + (sgi.threaded ? "1" : "0") + ",\n";
            sout += "unread: " + funread + ", issent: " + issent + ", millis: " + messagesInfo.millis + " }\n";

        } else {
            sout += "total:0,\nstart:0,\nlimit:0,\nmessages: [\n";
            sout += "\n], unread: 0, issent: false }\n";
        }
        out.println(sout);
    } catch (Exception exc) {
        new JsonResult(exc).printTo(out);
        Service.logger.error("Exception", exc);
    }
}