Example usage for javax.mail Folder READ_ONLY

List of usage examples for javax.mail Folder READ_ONLY

Introduction

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

Prototype

int READ_ONLY

To view the source code for javax.mail Folder READ_ONLY.

Click Source Link

Document

The Folder is read only.

Usage

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

/**
   Change the Flags of the messages the user selected.
        /* ww  w . j  a  v a2s  .co m*/
*/
public void setFlags(String folderhash, HTTPRequestHeader head) throws MessagingException {
    if (head.isContentSet("copymovemsgs") && head.getContent("COPYMOVE").equals("COPY")) {
        copyMoveMessage(folderhash, head.getContent("TO"), head, false);
    } else if (head.isContentSet("copymovemsgs") && head.getContent("COPYMOVE").equals("MOVE")) {
        copyMoveMessage(folderhash, head.getContent("TO"), head, true);
    } else if (head.isContentSet("flagmsgs")) {
        log.debug("setting message flags");
        Folder folder = getFolder(folderhash);

        //log.debug("Processing Request Header...");

        /* Get selected messages */
        int msgs[] = getSelectedMessages(head, folder.getMessageCount());

        //log.debug("get flags...");

        /* Get selected flags */
        Flags fl = new Flags(Flags.Flag.USER);
        if (head.getContent("MESSAGE FLAG").equals("DELETED")) {
            fl = new Flags(Flags.Flag.DELETED);
            if (need_expunge_folders == null) {
                need_expunge_folders = new Vector<String>();
            }
            need_expunge_folders.addElement(folderhash);
        } else if (head.getContent("MESSAGE FLAG").equals("SEEN")) {
            fl = new Flags(Flags.Flag.SEEN);
        } else if (head.getContent("MESSAGE FLAG").equals("RECENT")) {
            fl = new Flags(Flags.Flag.RECENT);
        } else if (head.getContent("MESSAGE FLAG").equals("ANSWERED")) {
            fl = new Flags(Flags.Flag.ANSWERED);
        } else if (head.getContent("MESSAGE FLAG").equals("DRAFT")) {
            fl = new Flags(Flags.Flag.DRAFT);
        }

        boolean value = true;
        if (head.getContent("MARK").equals("UNMARK")) {
            value = false;
        }

        //log.debug("Done!");
        //log.debug("Setting flags...");

        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgs, fl, value);
            if (user.getBoolVar("autoexpunge")) {
                folder.close(true);
                if (need_expunge_folders != null) {
                    need_expunge_folders.removeElement(folderhash);
                }
            } else {
                folder.close(false);
            }
        }

        folder.open(Folder.READ_WRITE);
        refreshFolderInformation(folderhash);
    }
}

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

/**
 * Copy or move the selected messages from folder fromfolder to folder tofolder.
 *//*w  ww  .  ja  v  a 2  s. c o  m*/
public void copyMoveMessage(String fromfolder, String tofolder, HTTPRequestHeader head, boolean move)
        throws MessagingException {
    Folder from = getFolder(fromfolder);
    Folder to = getFolder(tofolder);
    if (user.wantsSetFlags()) {
        if (from.isOpen() && from.getMode() == Folder.READ_ONLY) {
            from.close(false);
            from.open(Folder.READ_WRITE);
        } else if (!from.isOpen()) {
            from.open(Folder.READ_WRITE);
        }
        if (to.isOpen() && to.getMode() == Folder.READ_ONLY) {
            to.close(false);
            to.open(Folder.READ_WRITE);
        } else if (!to.isOpen()) {
            to.open(Folder.READ_WRITE);
        }
    } else {
        if (!from.isOpen()) {
            from.open(Folder.READ_ONLY);
        }
        if (to.isOpen() && to.getMode() == Folder.READ_ONLY) {
            to.close(false);
            to.open(Folder.READ_WRITE);
        } else if (!to.isOpen()) {
            to.open(Folder.READ_WRITE);
        }
    }
    int m[] = getSelectedMessages(head, from.getMessageCount());
    Message msgs[] = from.getMessages(m);
    from.copyMessages(msgs, to);
    if (move && user.wantsSetFlags()) {
        from.setFlags(m, new Flags(Flags.Flag.DELETED), true);
        if (user.getBoolVar("autoexpunge")) {
            from.close(true);
            to.close(true);
        } else {
            if (need_expunge_folders == null) {
                need_expunge_folders = new Vector<String>();
            }
            need_expunge_folders.addElement(fromfolder);
            from.close(false);
            to.close(false);
        }
    } else {
        from.close(false);
        if (user.getBoolVar("autoexpunge")) {
            to.close(true);
        } else {
            to.close(false);
        }
    }
    from.open(Folder.READ_WRITE);
    to.open(Folder.READ_WRITE);
    refreshFolderInformation(fromfolder);
    refreshFolderInformation(tofolder);
}

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

/**
 *
 * @param pop3Host// w w  w  .j a  va2 s.  c  o  m
 * @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:com.sonicle.webtop.mail.Service.java

public void processGetAttachment(HttpServletRequest request, HttpServletResponse response) {
    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 pcid = request.getParameter("cid");
    String purl = request.getParameter("url");
    String punknown = request.getParameter("unknown");
    String psaveas = request.getParameter("saveas");

    try {/*w ww  .  ja va 2 s  . c o  m*/
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        IMAPMessage im = (IMAPMessage) m;
        im.setPeek(us.isManualSeen());
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = null;
        if (pcid != null) {
            part = mailData.getCidPart(pcid);
        } else if (purl != null) {
            part = mailData.getUrlPart(purl);
        } else if (pidattach != null) {
            part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
        } else if (punknown != null) {
            part = mailData.getUnknownPart(Integer.parseInt(punknown));
        }

        //boolean wasseen = m.isSet(Flags.Flag.SEEN);
        if (part != null) {
            String ctype = "binary/octet-stream";
            if (psaveas == null) {
                ctype = part.getContentType();
                int ix = ctype.indexOf(";");
                if (ix > 0)
                    ctype = ctype.substring(0, ix);
            }
            String name = part.getFileName();
            if (name == null)
                name = "";
            try {
                name = MailUtils.decodeQString(name);
            } catch (Exception exc) {
            }
            name = name.trim();
            if (psaveas == null) {
                int ix = name.lastIndexOf(".");
                if (ix > 0) {
                    //String ext=name.substring(ix+1);
                    String xctype = ServletHelper.guessMediaType(name);
                    if (xctype != null)
                        ctype = xctype;
                }
            }
            ServletUtils.setFileStreamHeaders(response, ctype, DispositionType.INLINE, name);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen())
                    folder.open(Folder.READ_ONLY);
            }
            InputStream is = part.getInputStream();
            OutputStream out = response.getOutputStream();
            fastStreamCopy(is, out);
            is.close();
            out.close();
            //if(!wasseen){
            //   if (us.isManualSeen()) {
            //   m.setFlag(Flags.Flag.SEEN, false);
            //   }
            //}
        }
        im.setPeek(false);

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

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

public void processGetAttachments(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pids[] = request.getParameterValues("ids");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");

    try {//from  ww  w .j a  va  2 s.  c  om
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        String name = m.getSubject();
        if (name == null) {
            name = "attachments";
        }
        try {
            name = MailUtils.decodeQString(name);
        } catch (Exception exc) {
        }
        name += ".zip";
        //prepare hashmap to hold already used pnames
        HashMap<String, String> pnames = new HashMap<String, String>();
        ServletUtils.setFileStreamHeaders(response, "application/x-zip-compressed", DispositionType.INLINE,
                name);
        JarOutputStream jos = new java.util.jar.JarOutputStream(response.getOutputStream());
        byte[] b = new byte[64 * 1024];
        for (String pid : pids) {
            Part part = mailData.getAttachmentPart(Integer.parseInt(pid));
            String pname = part.getFileName();
            if (pname == null) {
                pname = "unknown";
            }
            /*
            try {
               pname = MailUtils.decodeQString(pname, "iso-8859-1");
            } catch (Exception exc) {
            }
            */
            //keep name and extension
            String bpname = pname;
            String extpname = null;
            int ix = pname.lastIndexOf(".");
            if (ix > 0) {
                bpname = pname.substring(0, ix);
                extpname = pname.substring(ix + 1);
            }
            //check for existing pname and find an unused name
            int xid = 0;
            String rpname = pname;
            while (pnames.containsKey(rpname)) {
                rpname = bpname + " (" + (++xid) + ")";
                if (extpname != null)
                    rpname += "." + extpname;
            }

            JarEntry je = new JarEntry(rpname);
            jos.putNextEntry(je);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen()) {
                    folder.open(Folder.READ_ONLY);
                }
            }
            InputStream is = part.getInputStream();
            int len = 0;
            while ((len = is.read(b)) != -1) {
                jos.write(b, 0, len);
            }
            is.close();

            //remember used pname
            pnames.put(rpname, rpname);
        }
        jos.closeEntry();
        jos.flush();
        jos.close();

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

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

public void processViewAttachment(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 pcid = request.getParameter("cid");
    String purl = request.getParameter("url");
    String punknown = request.getParameter("unknown");

    try {// www  .  ja v  a2s.co m
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = null;
        if (pcid != null) {
            part = mailData.getCidPart(pcid);
        } else if (purl != null) {
            part = mailData.getUrlPart(purl);
        } else if (pidattach != null) {
            part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
        } else if (punknown != null) {
            part = mailData.getUnknownPart(Integer.parseInt(punknown));
        }

        if (part != null) {
            String name = part.getFileName();
            if (name == null)
                name = "";
            try {
                name = MailUtils.decodeQString(name);
            } catch (Exception exc) {
            }
            name = name.trim();
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen())
                    folder.open(Folder.READ_ONLY);
            }

            String fileHash = AlgoUtils.md5Hex(new CompositeId(pfoldername, puidmessage, pidattach).toString());
            long lastModified = m.getReceivedDate().getTime();
            AttachmentViewerDocumentHandler docHandler = new AttachmentViewerDocumentHandler(false,
                    getEnv().getProfileId(), fileHash, part, lastModified);
            DocEditorManager.DocumentConfig config = getWts().prepareDocumentEditing(docHandler, name,
                    lastModified);

            new JsonResult(config).printTo(out);

        }
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

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

public void processPollAdvancedSearch(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {/*from  w ww  . j  av a  2  s .  c om*/
    CoreManager core = WT.getCoreManager();

    try {
        MailAccount account = getAccount(request);
        String sstart = request.getParameter("start");
        int start = 0;
        if (sstart != null) {
            start = Integer.parseInt(sstart);
        }
        String sout = "{\n";
        if (ast != null) {
            UserProfile profile = environment.getProfile();
            Locale locale = profile.getLocale();
            java.util.Calendar cal = java.util.Calendar.getInstance(locale);
            ArrayList<Message> msgs = ast.getResult();
            int totalrows = msgs.size();
            int newrows = totalrows - start;
            sout += "total:" + totalrows + ",\nstart:" + start + ",\nlimit:" + newrows + ",\nmessages: [\n";
            boolean first = true;
            for (int i = start; i < msgs.size(); ++i) {
                Message xm = msgs.get(i);
                if (xm.isExpunged()) {
                    continue;
                }
                IMAPFolder xmfolder = (IMAPFolder) xm.getFolder();
                boolean wasopen = xmfolder.isOpen();
                if (!wasopen)
                    xmfolder.open(Folder.READ_ONLY);
                long nuid = xmfolder.getUID(xm);
                if (!wasopen)
                    xmfolder.close(false);
                IMAPMessage m = (IMAPMessage) xm;
                //Date
                java.util.Date d = m.getSentDate();
                if (d == null) {
                    d = m.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);
                String xfolder = xm.getFolder().getFullName();
                FolderCache fc = account.getFolderCache(xfolder);
                String folder = StringEscapeUtils.escapeEcmaScript(xfolder);
                String foldername = StringEscapeUtils
                        .escapeEcmaScript(MailUtils.htmlescape(getInternationalFolderName(fc)));
                //From
                String from = "";
                Address ia[] = m.getFrom();
                if (ia != null) {
                    InternetAddress iafrom = (InternetAddress) ia[0];
                    from = iafrom.getPersonal();
                    if (from == null) {
                        from = iafrom.getAddress();
                    }
                }
                from = (from == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(from)));
                //To
                String to = "";
                ia = m.getRecipients(Message.RecipientType.TO);
                if (ia != null) {
                    InternetAddress iato = (InternetAddress) ia[0];
                    to = iato.getPersonal();
                    if (to == null) {
                        to = iato.getAddress();
                    }
                }
                to = (to == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(to)));
                //Subject
                String subject = m.getSubject();
                if (subject != null) {
                    try {
                        subject = MailUtils.decodeQString(subject);
                    } catch (Exception exc) {

                    }
                }
                subject = (subject == null ? ""
                        : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject)));
                //Unread
                boolean unread = !m.isSet(Flags.Flag.SEEN);
                //if (ppattern==null && unread) ++funread;
                //Priority
                int priority = getPriority(m);
                //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;
                if (d != null) {
                    cal1.setTime(today);
                    cal2.setTime(d);
                    if (cal1.get(java.util.Calendar.DAY_OF_MONTH) == cal2.get(java.util.Calendar.DAY_OF_MONTH)
                            && cal1.get(java.util.Calendar.MONTH) == cal2.get(java.util.Calendar.MONTH)
                            && cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)) {
                        isToday = true;
                    }
                }

                Flags flags = m.getFlags();
                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 = (m.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) {
                    cflag += "-complete";
                }

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

                boolean hasNote = flags.contains(sflagNote);

                sout += "{folder:'" + folder + "', folderdesc:'" + foldername + "',idmandfolder:'" + folder
                        + "|" + nuid + "',idmessage:'" + nuid + "',priority:" + priority + ",status:'" + status
                        + "',to:'" + to + "',from:'" + from + "',subject:'" + subject + "',date: new Date("
                        + yyyy + "," + mm + "," + dd + "," + hhh + "," + mmm + "," + sss + "),unread: " + unread
                        + ",size:" + msgsize + ",flag:'" + cflag + "'" + (archived ? ",arch:true" : "")
                        + (isToday ? ",istoday:true" : "") + (hasNote ? ",note:true" : "") + "}";
                first = false;
            }
            sout += "\n]\n, progress: " + ast.getProgress() + ", curfoldername: '"
                    + StringEscapeUtils.escapeEcmaScript(getInternationalFolderName(ast.getCurrentFolder()))
                    + "', " + "max: " + ast.isMoreThanMax() + ", finished: "
                    + (ast.isFinished() || ast.isCanceled() || !ast.isRunning()) + " }\n";
        } else {
            sout += "total:0,\nstart:0,\nlimit:0,\nmessages: [\n";
            sout += "\n] }\n";
        }
        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}