Example usage for javax.mail Folder READ_WRITE

List of usage examples for javax.mail Folder READ_WRITE

Introduction

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

Prototype

int READ_WRITE

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

Click Source Link

Document

The state and contents of this folder can be modified.

Usage

From source file:com.ikon.util.MailUtils.java

/**
 * Test IMAP connection//w ww.  ja v a2  s .  c o  m
 */
public static void testConnection(MailAccount ma) throws IOException {
    log.debug("testConnection({})", ma);
    Session session = Session.getDefaultInstance(getProperties());
    Store store = null;
    Folder folder = null;

    try {
        store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());
        folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        folder.close(false);
    } catch (NoSuchProviderException e) {
        throw new IOException(e.getMessage());
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        // Try to close folder
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }

        // Try to close store
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException e) {
                throw new IOException(e.getMessage());
            }
        }
    }

    log.debug("testConnection: void");
}

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

public SetMessageResponseType deleteMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;//  ww  w  .ja v a  2  s.  c  om
    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:com.funambol.email.items.manager.ImapEntityManager.java

/**
 * @param filter EmailFilter/*from   w  w w . j  a  va2s . c om*/
 * @param mailId  mail id; String
 * @param parentId parent id; String
 * @param status status of the item; char
 * @param source_uri  String
 * @param principalId princiapal ID long
 * @return Email
 * @throws EntityException
 */
public Email getEmailFromUID(EmailFilter filter, String mailId, String parentId, char status, String source_uri,
        long principalId, String username, ContentProviderInfo contentProviderInfo) throws EntityException {

    if (log.isTraceEnabled()) {
        log.trace("getItemByUID in folder " + parentId + " mail: " + mailId + " status " + status);
    }

    Email emailOut = null;
    ItemMessage im = null;
    String fullpath = null;
    long FMID = 0;

    try {
        FMID = Long.parseLong(mailId);
        fullpath = this.ied.getFullPathFromFID(parentId, source_uri, principalId, username);
    } catch (Exception e) {
        throw new EntityException(e);
    }

    timeStart = System.currentTimeMillis();

    if (fullpath != null && FMID != 0) {

        if (parentId.equalsIgnoreCase(Def.FOLDER_INBOX_ID)) {
            // inbox folder
            try {
                if (!this.imsw.folderInboxOpened.isOpen()) {
                    this.imsw.folderInboxOpened.open(javax.mail.Folder.READ_WRITE);
                }
                im = this.getEmailFromUID(filter, this.imsw.folderInboxOpened, parentId, FMID, status,
                        source_uri, principalId, username, contentProviderInfo);
            } catch (MessagingException e) {
                throw new EntityException(e);
            } catch (EntityException e) {
                throw new EntityException(e);
            }

        } else {
            // rest of the folders
            IMAPFolder f = null;
            try {
                f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath);
                if (f.exists()) {
                    if (!f.isOpen()) {
                        f.open(Folder.READ_WRITE);
                    }
                    im = this.getEmailFromUID(filter, f, parentId, FMID, status, source_uri, principalId,
                            username, contentProviderInfo);
                } else {
                    return emailOut;
                }
            } catch (Exception e) {
                throw new EntityException(e);
            } finally {
                if (f != null) {
                    try {
                        if (f.isOpen()) {
                            f.close(true);
                            timeStop = System.currentTimeMillis();
                            if (log.isTraceEnabled()) {
                                log.trace("getItem Total Execution Time: " + (timeStop - timeStart) + " ms");
                            }
                        }
                    } catch (MessagingException me) {
                        throw new EntityException(me);
                    }
                }
            }
        }
    }

    if (im != null) {
        try {
            emailOut = createFoundationMail(im);
        } catch (Exception e) {
            throw new EntityException(e);
        }
    }

    return emailOut;
}

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

private SetMessageResponseType saveDraft(SetMessageRequestType request, String[] access, IMAPSSLStore sslStore,
        String destinationFolder, Session session) throws MessagingException {
    SetMessageResponseType response = new SetMessageResponseType();
    Folder folder = getImapFolder(session, sslStore, access, destinationFolder);
    folder.open(Folder.READ_WRITE);
    IMAPMessage imapMessage = null;/*from  w w w . j a  v a 2s .  c  o m*/
    Message[] msgArr = null;
    try {
        msgArr = createMessage(session, access[0], request);
        folder.appendMessages(msgArr);
    } catch (Exception e) {
        log.error("Error creating draft message");
        response.setSuccessStatus(false);
        response.setMessage("Error saving draft message for user = " + request.getUserId());
        e.printStackTrace();
        return response;
    }
    response.setSuccessStatus(true);
    response.setMessage(" ");
    return response;
}

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

/**
 * This methog //  ww w . j a  v  a 2  s .  co m
 * @param message
 * @param request
 * @param session
 * @throws Exception 
 */
private void sendMessagesTOCCBCC(Message[] message, SetMessageRequestType request, Session session)
        throws Exception {
    IMAPFolder folder = null;
    IMAPSSLStore sslStore = null;
    Set<String> allContacts = new HashSet<String>();

    //DBG - Check about CC entry.
    List<String> ctlist = request.getContactTo();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> TO=" + ctlist.get(0));
    }
    ctlist = request.getContactCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> CC=" + ctlist.get(0));
    }
    ctlist = request.getContactBCC();
    if (!CommonUtil.listNullorEmpty(ctlist)) {
        System.out.println("===> BCC=" + ctlist.get(0));
    }

    if (!CommonUtil.listNullorEmpty(request.getContactTo())) {
        allContacts.addAll(request.getContactTo());
    }

    if (!CommonUtil.listNullorEmpty(request.getContactCC())) {
        allContacts.addAll(request.getContactCC());
    }

    if (!CommonUtil.listNullorEmpty(request.getContactBCC())) {
        allContacts.addAll(request.getContactBCC());
    }

    try {

        for (String ctcName : allContacts) {

            System.out.println("===> Looking for Contact of given CN=" + ctcName);

            if (CommonUtil.strNullorEmpty(ctcName)) {
                continue;
            }

            ContactDTO dto = findContactByCn(ctcName);
            List<String> acctPass = getContactEmailAndPass(dto);
            String[] access = acctPass.toArray(new String[0]);

            System.out.println("===> Sending to Contact=" + access[0] + " mapped from given CN=" + ctcName);

            URLName urlName = new URLName(mailUrl);
            sslStore = new IMAPSSLStore(session, urlName);
            sslStore.connect(host, access[0], access[1]);

            folder = (IMAPFolder) sslStore.getFolder(this.mapKmrLocationToImapFolder("INBOX", this.host));
            folder.open(Folder.READ_WRITE);
            folder.appendMessages(message);
            folder.close(false);
            sslStore.close();
        }

    } catch (Exception e) {
        log.error("Error sending TO, CC and BCC emails: " + e.getMessage());
    } 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");
            }
        }
    }
}

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

/**
 * Opens a folder and print all msgs found.
 * @param folder// w w w  .j av a  2s.  c o m
 * @param userId
 * @param pwd
 */
void printAllMsgs(String folderName, String userId, String pwd) throws MessagingException {
    IMAPSSLStore sslStore = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);
    String[] access = new String[2];
    access[0] = userId;
    access[1] = pwd;

    Folder folder = getImapFolder(session, sslStore, access, folderName);
    folder.open(Folder.READ_WRITE);

    try {
        this.printAllMsgs(folder.getMessages());

    } catch (MessagingException ex) {
        System.out.println("ERROR at printAllEmailMsgs.");
    }
}

From source file:com.funambol.email.items.manager.ImapEntityManager.java

/**
 * get messages from folders.//from  w w  w  . j a va2 s  .  c  o m
 * the cache is not filter dependent. This method
 * return all the items in the server without filter
 *
 * @param fullpath path of the folder
 * @param folderId parent id
 * @param filter   EmailFilter
 * @return map with all mail server CrcSyncItemInfo
 * @throws EntityException
 */
private LinkedHashMap getAllEmailsInfoRest(String fullpath, String FID, EmailFilter filter)
        throws EntityException {

    LinkedHashMap syncItemInfos = new LinkedHashMap();
    IMAPFolder f = null;
    Message msg = null;
    long lastCRC = 0;
    String messageID = null;
    java.util.Date headerDate = null;
    String internal = null;
    String internalS = null;
    int itemsNum = 0;
    String GUID = null;
    String FMID = null;
    String UIDV = null;
    EntityException finalExc = null;

    try {

        f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath);

        // check folder
        if (!f.exists()) {
            return syncItemInfos;
        }

        timeStart = System.currentTimeMillis();

        f.open(Folder.READ_WRITE);

        Message[] items = this.ied.getAllEmails(f, FID, filter);

        // we use a fetch method in the imap protocol (not in the pop)
        if (items != null) {

            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            f.fetch(items, fp);

            // create the info
            itemsNum = items.length;

            for (int i = 0; i < itemsNum; i++) {

                msg = items[i];

                messageID = Utility.getHeaderMessageID(msg);

                try {
                    // REVIEWED THE FILTER TIME STRATEGY
                    //headerDate = UtilityDate.getHeaderDate(msg,null);
                    headerDate = UtilityDate.getDateForTimeFilter(msg, null);
                } catch (Exception e) {
                    log.error("Error parsing header date for Caching System ", e);
                }

                //String dateForCRC = Utility.getHeaderDateForCRC(msg);
                //lastCRC   = Utility.createCRC(msg, messageID, dateForCRC);
                String flagList = Utility.createFlagsList(msg);
                lastCRC = Utility.createCRC(flagList, Def.PROTOCOL_IMAP);

                FMID = String.valueOf(f.getUID(msg));
                UIDV = String.valueOf(f.getUIDValidity());
                GUID = Utility.createIMAPGUID(FID, FMID, UIDV);

                internalS = Utility.getHeaderSyncLabel(msg);
                if (internalS != null) {
                    internal = "Y";
                }

                SyncItemInfo sii = new SyncItemInfo(new SyncItemKey(GUID), lastCRC, messageID, headerDate, null,
                        null, null, null, internal, "Y", null);

                syncItemInfos.put(GUID, sii);

            }

        }

    } catch (MessagingException e) {
        throw new EntityException(e);
    } finally {
        if (f != null) {
            try {
                if (f.isOpen()) {
                    f.close(true);
                    timeStop = System.currentTimeMillis();
                    if (log.isTraceEnabled()) {
                        log.trace("getEmailsInfo Execution Time: " + (timeStop - timeStart) + " ms");
                    }
                }
            } catch (MessagingException me) {
                finalExc = new EntityException(me);
            }
        }
    }

    if (finalExc != null) {
        throw finalExc;
    }

    return syncItemInfos;

}

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

/**
 * Expunge all folders that have messages waiting to be deleted
 *///  w  w  w. ja  v  a 2  s. c o m
public void expungeFolders() {
    if (need_expunge_folders != null) {
        Enumeration<String> enumVar = need_expunge_folders.elements();
        while (enumVar.hasMoreElements()) {
            String hash = (String) enumVar.nextElement();
            if (user.wantsSetFlags()) {
                Folder f = getFolder(hash);
                try {
                    if (f.isOpen()) {
                        f.close(false);
                    }
                    f.open(Folder.READ_WRITE);
                    // POP3 doesn't support expunge!
                    try {
                        f.expunge();
                    } catch (MessagingException ex) {
                    }
                    f.close(true);
                } catch (MessagingException ex) {
                    // XXXX
                    log.error("Failed to expunge folders", ex);
                }
            }
        }
    }
}

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

/**
   Change the Flags of the messages the user selected.
        //  w ww .jav a  2  s.  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.
 *//*ww  w .j  a v a 2s  .co 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);
}