Example usage for javax.mail Folder open

List of usage examples for javax.mail Folder open

Introduction

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

Prototype

public abstract void open(int mode) throws MessagingException;

Source Link

Document

Open this Folder.

Usage

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 *
 * @param request/*from  w w  w .j  av a  2 s.  c  om*/
 *        where request.action = [ "Send" , "Update" ,"Read" , "Save" ]
 * @return
 */
private SetMessageResponseType sendImapSSLMail(SetMessageRequestType request) {

    //System.out.println("===> sendImapSSLMail: Action= " + request.getAction());

    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;
    Folder folder = null; //the email server folder the msg is CURRENTLY in.

    String userType = "";
    String[] access = new String[2];

    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDTO foundContact = null;
    try {
        foundContact = findContactByUserId(userId);
    } catch (Exception e) {
        log.error("Contact record not found for userid: " + request.getUserId());
        response.setMessage("Contact record not found for userid: " + request.getUserId());
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(foundContact.getCommonName(), foundContact.getUid());

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    // Use the sslStore to send/change the message
    try {
        //action = Save
        if (request.getAction().equalsIgnoreCase("Save")) {
            response = saveDraft(request, access, sslStore,
                    this.mapKmrLocationToImapFolder("Drafts", this.host), session);
            response.setSuccessStatus(true);
            //return response;
        }
        //action = Send
        else if (request.getAction().equalsIgnoreCase("Send")) {
            // create and send msg to recipient(s).
            Message[] msgArr = createMessage(session, access[0], request);
            sendMessagesTOCCBCC(msgArr, request, session);

            // Store a copy to sender's Sent folder
            folder = getImapFolder(session, sslStore, access,
                    this.mapKmrLocationToImapFolder("Sent", this.host));
            folder.appendMessages(msgArr);

            response.setSuccessStatus(true);
        }
        //action = ..any other..
        else {
            folder = getImapFolder(session, sslStore, access,
                    this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
            folder.open(Folder.READ_WRITE);

            //--------------------------------------------
            // Find the message by the given Message-ID
            //--------------------------------------------
            IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

            //--------------------------------------------
            // Process the message
            //--------------------------------------------
            if (imapMessage != null) {
                System.out.println("===> sendImapSSLMail:Updating:   action=" + request.getAction());
                System.out.println("===> sendImapSSLMail:Updating:   folder=" + folder.getName());
                System.out.println("===> sendImapSSLMail:Updating:ImapMsgID=" + imapMessage.getMessageID());

                updateImapSSLMail(request, folder, imapMessage);

                System.out.println("===> sendImapSSLMail: Done Setting " + request.getAction() + " for msgId="
                        + request.getMessageId());

                response.setSuccessStatus(true);

            } else {
                String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
                System.out.println("===> sendImapSSLMail: " + statMsg);

                response.setSuccessStatus(false);
                response.setMessage(statMsg);
            }

        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage("Error sending mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        return response;
    } finally {
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException me) {
                log.error("Error closing folder");
            }
        }
        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (MessagingException me) {
                log.error("Error closing SSLStore");
            }
        }
    }

    return response;

}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

public SetMessageResponseType deleteMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;//from   w  ww  . j  a v  a  2 s .  co m
    Folder sourceFolder = null;
    Folder targetFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN
    //        if (foundContact.getEmployeeNumber() != null) {
    //            userType = ITEM_ID_PROVIDER;
    //            access = retrieveMailAccess(userType, foundContact.getEmployeeNumber());
    //        }
    //        else {
    //            userType = ITEM_ID_PATIENT;
    //            access = retrieveMailAccess(userType, foundContact.getUid());
    //        }

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    try {

        //--------------------------
        // Set originating folder
        //--------------------------
        sourceFolder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));

        // Is this really needed if request comes in with location=UserTrash already?
        if (request.getAction().equals("Undelete")) {
            sourceFolder = getImapFolder(session, sslStore, access, "UserTrash");
        }
        sourceFolder.open(Folder.READ_WRITE);

        //--------------------------
        // Set destination folder
        //--------------------------
        if (request.getAction().equals("Delete")) {
            targetFolder = getImapFolder(session, sslStore, access, "UserTrash");
        }
        if (request.getAction().equals("DeleteForever")) {
            targetFolder = getImapFolder(session, sslStore, access, "AdminTrash");
        } else if (request.getAction().equals("Undelete")) {
            targetFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        targetFolder.open(Folder.READ_WRITE);

        //--------------------------------------------
        // Find the message by the given Message-ID
        //-------------------------------------------
        Message msg = this.findMsgByMessageId(sourceFolder, request.getMessageId());

        if (msg == null) {
            String errmsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> deleteMessage: " + errmsg);

            response.setSuccessStatus(false);
            response.setMessage(errmsg);

        } else {

            //this.printMsgIdSubject(msg); //DBG printout

            //----------------------
            //copy to new folder
            //----------------------
            Message[] messages = new Message[] { msg };
            sourceFolder.copyMessages(messages, targetFolder);

            //----------------------
            //remove from old folder
            //----------------------
            msg.setFlag(Flags.Flag.DELETED, true);
            sourceFolder.expunge();

            response.setSuccessStatus(true);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage("Error archiving mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;
    } finally {
        try {
            sourceFolder.close(false);
            targetFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}

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

/**
 * Construct the folder subtree for the given folder and append it to
 * xml_parent./*from   w  w  w .ja  v  a  2s.c  o  m*/
 *
 * N.b. this method does not necessarily create a new XML Folder Element.
 * If called with subscribed_only and the target Folder (and in some
 * cases its descendants) are not subscribed, no Element will be created
 * and 0 will be returned.
 * <P>
 * Pop servers don't support nesting at all, so you'll just get a single
 * level out of this method.
 * <P>
 * There is a critical subscribed_only difference in behavior between
 * Maildir and mbox type mail servers.
 * Maildir folders are all HOLDS_MESSAGES, whether empty or not, and
 * these folders have a subscribed attribute which the user can set,
 * and which we honor.
 * mbox folders, on the other hand, have no subscribed attribute for
 * their !HOLDS_MESSAGE folders, so we must recurse to all of the
 * descendant HOLDS_MESSAGE folders to see if we should show.
 *
 * @param folder the folder where we begin
 * @param xml_parent XML Element where the gathered information will be
 *                   appended
 * @param subscribed_only Only add 'subscribed' folders
 * @param doCount Whether to generate message counts for Elements
 *                corresponding to HOLDS_MESSAGE folders.
 * @returns maximum depth of the folder tree (needed to calculate the
 *     necessary columns in a table).  Returns 0 if no XML elements added.
 */
protected int getFolderTree(Folder folder, Element xml_parent, boolean subscribed_only, boolean doCount) {
    int generatedDepth = 0;
    int folderType;
    Element xml_folder;

    try {
        folderType = folder.getType();
    } catch (MessagingException ex) {
        log.error("Can't get enough info from server to even make Gui node", ex);
        xml_parent.setAttribute("error", "For child '" + folder.getName() + ":  " + ex.getMessage());
        return 0;
    }
    boolean holds_folders = (folderType & Folder.HOLDS_FOLDERS) != 0;
    boolean holds_messages = (folderType & Folder.HOLDS_MESSAGES) != 0;
    // Sanity check:
    if ((!holds_folders) && !holds_messages) {
        log.fatal("Folder can hold neither folders nor messages: " + folder.getFullName());
        throw new RuntimeException("Folder can hold neither folders nor messages: " + folder.getFullName());
    }
    if (subscribed_only && holds_messages && !folder.isSubscribed())
        return generatedDepth; // Return right away and save a LOT OF WORK
    // N.b. we honor folder.isSubscribed() only for holds_message
    // folders.  That means all Maildir server folders, and all
    // mbox server folders except for mbox directories.  In this
    // last case, we must recurse to determine whether to show folder.
    String id = generateFolderHash(folder);
    xml_folder = model.createFolder(id, folder.getName(), holds_folders, holds_messages);
    // XMLUserModel.createFolder() declares no throws.  If any Exceptions
    // are expected from it, move the statement above into the try block.
    // The xml_folder Element here will be orphaned and GC'd if we don't
    // appendChild (in which case we return 0).

    if (doCount && holds_messages)
        try {
            // this folder will definitely be added!
            /* This folder can contain messages */
            Element messagelist = model.createMessageList();

            int total_messages = folder.getMessageCount();
            int new_messages = folder.getNewMessageCount();

            if (total_messages == -1 || new_messages == -1 || !folder.isOpen()) {
                folder.open(Folder.READ_ONLY);
                total_messages = folder.getMessageCount();
                new_messages = folder.getNewMessageCount();
            }
            if (folder.isOpen())
                folder.close(false);

            messagelist.setAttribute("total", total_messages + "");
            messagelist.setAttribute("new", new_messages + "");
            log.debug("Counted " + new_messages + '/' + total_messages + " for folder " + folder.getFullName());
            xml_folder.appendChild(messagelist);
        } catch (MessagingException ex) {
            log.warn("Failed to count messages in folder '" + folder.getFullName() + "'", ex);
            xml_folder.setAttribute("error", ex.getMessage());
        }

    int descendantDepth = 0;
    if (holds_folders)
        try {
            Set<String> fullNameSet = new HashSet<String>();

            /* Recursively add subfolders to the XML model */
            // DO NOT USE listSubscribed(), because with !HOLDS_MESSAGE
            // folders, that skips non-Message Folders which may contain
            // subscribed descendants!
            for (Folder f : folder.list()) {
                if (!fullNameSet.add(f.getFullName())) {
                    log.warn("Skipping duplicate subfolder returned by mail" + " server:  " + f.getFullName());
                    continue;
                }
                if (subscribed_only && (f.getType() & Folder.HOLDS_MESSAGES) != 0 && !f.isSubscribed())
                    continue;
                /* If we recursed here, the getFolderTree() would
                 * just return 0 and no harm done.
                 * Just helping performance by preventing a recursion
                 * here.
                 * For comment on the logic here, see the same test
                 * towards the top of this method (before recursion).
                 */
                int depth = getFolderTree(f, xml_folder, subscribed_only, doCount);
                if (depth > descendantDepth)
                    descendantDepth = depth;
            }
            generatedDepth += descendantDepth;
        } catch (MessagingException ex) {
            xml_folder.setAttribute("error", ex.getMessage());
        }

    // We've already validated that if subscribed_only and holds_message
    //  then folder is subcribed.  Also verified either holds_m or holds_f.
    //  Only have to check the !holds_message case.
    if (subscribed_only && (!holds_messages) && descendantDepth < 1) {
        xml_folder = null;
        // Unnecessary, but may encourage GC
        return generatedDepth;
    }

    /* We ALWAYS return only subscribed folders except for these two
     * distinct cases: */
    xml_folder.setAttribute("subscribed",
            ((holds_messages && !folder.isSubscribed()) || ((!holds_messages) && descendantDepth < 1)) ? "false"
                    : "true");
    // N.b. our Element's "subscribed" element does not correspond 1:1
    // to Folder.isSubscribed(), since non-message-holding Folders have
    // no "subscribed" attribute.
    folders.put(id, folder);

    xml_parent.appendChild(xml_folder);
    generatedDepth++; // Add the count for xml_folder
    return generatedDepth;
}

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 {/*from w ww .  ja  v  a  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);
        }
        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 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 {/*from   w w w  . j av  a  2s . com*/
        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 w  ww  . ja  v a2 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);
    }
}