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:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Flag a given {@link GmailMessage} as Starred.
 *
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if unable to flag {@link GmailMessage} as starred
 *//*from  w  w  w. ja  v a  2 s  .c  o m*/
public void addStar(int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid " + "GmailMessage number");
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(this.srcFolder, store);
        folder.open(Folder.READ_WRITE);
        Message message = folder.getMessage(messageNumber);
        if (!message.isSet(Flags.Flag.FLAGGED)) {
            message.setFlag(Flags.Flag.FLAGGED, true);
        }
    } catch (Exception e) {
        throw new GmailException(
                "ImapGmailClient failed flagging" + " GmailMessage as starred : " + messageNumber, e);
    } finally {
        closeFolder(folder);
    }
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * Retrieve mail messages in a JSON representation
 * //from ww  w .  j a va 2 s  .c  om
 * @return
 */
public JSONArray getJMessages() {

    JSONArray jMessages = new JSONArray();
    if (store == null)
        return jMessages;

    try {
        /*
         * Connect to IMAP store
         */
        store.connect();

        /*
         * Retrieve & open INBOX folder
         */
        Folder folder = store.getFolder(ImapConstants.INBOX);
        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        for (int i = 0; i < messages.length; i++) {

            Message m = messages[i];

            JSONObject jMessage = new JSONObject();

            jMessage.put(ImapConstants.J_KEY, ""); // introduced to be compatible with posted emails             
            jMessage.put(ImapConstants.J_ID, i); // message identifier to retrieve from external server

            jMessage.put(ImapConstants.J_SUBJECT, m.getSubject());
            jMessage.put(ImapConstants.J_DATE, m.getSentDate());

            String from = "";

            Address[] addresses = m.getFrom();
            for (Address address : addresses) {

                InternetAddress internetAddress = (InternetAddress) address;
                from = internetAddress.getPersonal();

            }

            jMessage.put(ImapConstants.J_FROM, from);

            FileUtil attachment = getAttachment(m);
            if (attachment == null) {
                jMessage.put(ImapConstants.J_ATTACHMENT, false);

            } else {
                jMessage.put(ImapConstants.J_ATTACHMENT, true);

            }

            jMessages.put(jMessages.length(), jMessage);

        }

        folder.close(false);
        store.close();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
    }

    return jMessages;
}

From source file:be.ibridge.kettle.job.entry.getpop.JobEntryGetPOP.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);/*from   w  w w.  j  av a2  s.  c o  m*/
    result.setNrErrors(1);

    FileObject fileObject = null;

    //Get system properties

    //Properties prop = System.getProperties();
    Properties prop = new Properties();

    //Create session object
    //Session sess = Session.getDefaultInstance(prop,null);
    Session sess = Session.getInstance(prop, null);
    sess.setDebug(true);

    try {

        int nbrmailtoretrieve = Const.toInt(firstmails, 0);
        fileObject = KettleVFS.getFileObject(getRealOutputDirectory());

        // Check if output folder exists
        if (!fileObject.exists()) {
            log.logError(toString(),
                    Messages.getString("JobGetMailsFromPOP.FolderNotExists1.Label") + getRealOutputDirectory()
                            + Messages.getString("JobGetMailsFromPOP.FolderNotExists2.Label"));
        } else {

            String host = getRealServername();
            String user = getRealUsername();
            String pwd = getRealPassword();

            Store st = null;

            if (!getUseSSL()) {

                //Create POP3 object               
                st = sess.getStore("pop3");

                // Try to connect to the server
                st.connect(host, user, pwd);
            } else {
                // Ssupports POP3 connection with SSL, the connection is established via SSL.

                String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

                //Properties pop3Props = new Properties();

                prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
                prop.setProperty("mail.pop3.socketFactory.fallback", "false");
                prop.setProperty("mail.pop3.port", getRealSSLPort());
                prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort());

                URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd);

                st = new POP3SSLStore(sess, url);

                st.connect();

            }

            log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user);

            //Open default folder   INBOX 
            Folder f = st.getFolder("INBOX");
            f.open(Folder.READ_ONLY);

            if (f == null) {
                log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label"));

            } else {

                log.logDetailed(toString(),
                        Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder1.Label") + f.getName()
                                + Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder2.Label")
                                + f.getMessageCount());
                log.logDetailed(toString(),
                        Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder1.Label") + f.getName()
                                + Messages.getString("JobGetMailsFromPOP.TotalNewMessagesFolder2.Label")
                                + f.getNewMessageCount());

                // Get emails 
                Message msg_list[] = getPOPMessages(f, retrievemails);

                if (msg_list.length > 0) {
                    List current_file_POP = new ArrayList();
                    List current_filepath_POP = new ArrayList();
                    int nb_email_POP = 1;
                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");

                    String startpattern = "name";
                    if (!Const.isEmpty(getRealFilenamePattern())) {
                        startpattern = getRealFilenamePattern();
                    }

                    for (int i = 0; i < msg_list.length; i++)

                    {

                        /*if(msg[i].isMimeType("text/plain"))
                         {
                         log.logDetailed(toString(), "Expediteur: "+msg[i].getFrom()[0]);
                         log.logDetailed(toString(), "Sujet: "+msg[i].getSubject());
                         log.logDetailed(toString(), "Texte: "+(String)msg[i].getContent());
                                
                         }*/

                        if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2) || (retrievemails != 2)) {

                            Message msg_POP = msg_list[i];
                            log.logDetailed(toString(), Messages.getString("JobGetMailsFromPOP.EmailFrom.Label")
                                    + msg_list[i].getFrom()[0]);
                            log.logDetailed(toString(),
                                    Messages.getString("JobGetMailsFromPOP.EmailSubject.Label")
                                            + msg_list[i].getSubject());

                            String localfilename_message = startpattern + "_" + dateFormat.format(new Date())
                                    + "_" + (i + 1) + ".mail";

                            log.logDetailed(toString(),
                                    Messages.getString("JobGetMailsFromPOP.LocalFilename1.Label")
                                            + localfilename_message
                                            + Messages.getString("JobGetMailsFromPOP.LocalFilename2.Label"));

                            File filename_message = new File(getRealOutputDirectory(), localfilename_message);
                            OutputStream os_filename = new FileOutputStream(filename_message);
                            Enumeration enums_POP = msg_POP.getAllHeaders();
                            while (enums_POP.hasMoreElements())

                            {
                                Header header_POP = (Header) enums_POP.nextElement();
                                os_filename.write(new StringBuffer(header_POP.getName()).append(": ")
                                        .append(header_POP.getValue()).append("\r\n").toString().getBytes());
                            }
                            os_filename.write("\r\n".getBytes());
                            InputStream in_POP = msg_POP.getInputStream();
                            byte[] buffer_POP = new byte[1024];
                            int length_POP = 0;
                            while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) {
                                os_filename.write(buffer_POP, 0, length_POP);
                            }
                            os_filename.close();
                            nb_email_POP++;
                            current_file_POP.add(filename_message);
                            current_filepath_POP.add(filename_message.getPath());

                            if (delete) {
                                log.logDetailed(toString(),
                                        Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label"));
                                msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true);
                            }
                        }

                    }
                }
                // Close and exit 
                if (f != null)
                    f.close(false);
                if (st != null)
                    st.close();

                f = null;
                st = null;
                sess = null;

                result.setNrErrors(0);
                result.setResult(true);

            }
        }

    }

    catch (NoSuchProviderException e) {
        log.logError(toString(), "provider error: " + e.getMessage());
    } catch (MessagingException e) {
        log.logError(toString(), "Message error: " + e.getMessage());
    }

    catch (Exception e) {
        log.logError(toString(), "Inexpected error: " + e.getMessage());
    }

    finally {
        if (fileObject != null) {
            try {
                fileObject.close();
            } catch (IOException ex) {
            }
            ;
        }
        sess = null;

    }

    return result;
}

From source file:jp.mamesoft.mailsocketchat.Mail.java

public void run() {
    while (true) {
        try {/*from w w  w  . j  a v a2s  . co m*/
            System.out.println("????");
            Properties props = System.getProperties();

            // Get a Session object
            Session session = Session.getInstance(props, null);
            // session.setDebug(true);

            // Get a Store object
            Store store = session.getStore("imaps");

            // Connect
            store.connect("imap.gmail.com", 993, Mailsocketchat.mail_user, Mailsocketchat.mail_pass);
            System.out.println("??????");

            // Open a Folder
            Folder folder = store.getFolder("INBOX");
            if (folder == null || !folder.exists()) {
                System.out.println("IMAP??????");
                System.exit(1);
            }

            folder.open(Folder.READ_WRITE);

            // Add messageCountListener to listen for new messages
            folder.addMessageCountListener(new MessageCountAdapter() {
                public void messagesAdded(MessageCountEvent ev) {
                    Message[] msgs = ev.getMessages();

                    // Just dump out the new messages
                    for (int i = 0; i < msgs.length; i++) {
                        try {
                            System.out.println("?????");
                            InternetAddress addrfrom = (InternetAddress) msgs[i].getFrom()[0];
                            String subject = msgs[i].getSubject();
                            if (subject == null) {
                                subject = "";
                            }

                            Pattern hashtag_p = Pattern.compile("#(.+)");
                            Matcher hashtag_m = hashtag_p.matcher(subject);

                            if (subject.equals("#")) {
                                hashtag = null;
                            } else if (hashtag_m.find()) {
                                hashtag = hashtag_m.group(1);
                            }

                            String comment = msgs[i].getContent().toString().replaceAll("\r\n", " ");
                            comment = comment.replaceAll("\n", " ");
                            comment = comment.replaceAll("\r", " ");
                            JSONObject data = new JSONObject();
                            data.put("comment", comment);
                            if (hashtag != null) {
                                data.put("channel", hashtag);
                            }
                            if (!comment.equals("") && !comment.equals(" ") && !comment.equals("  ")) {
                                Mailsocketchat.socket.emit("say", data);
                                System.out.println("????");
                            }

                            //
                            if (subject.equals("push") || subject.equals("Push")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 2);
                                Mailsocketchat.push = true;
                                Mailsocketchat.repeat = false;
                                Mailsocketchat.address = addrfrom.getAddress();
                                repeatthread.cancel();
                                repeatthread = null;
                                System.out.println("?????");
                            } else if (subject.equals("fetch") || subject.equals("Fetch")
                                    || subject.equals("?")) {
                                Send(addrfrom.getAddress(), 3);
                                Mailsocketchat.push = false;
                                Mailsocketchat.repeat = false;
                                repeatthread.cancel();
                                repeatthread = null;
                                System.out.println("??????");
                            } else if (subject.equals("repeat") || subject.equals("Repeat")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 7);
                                Mailsocketchat.push = false;
                                Mailsocketchat.repeat = true;
                                Mailsocketchat.address = addrfrom.getAddress();
                                if (repeatthread == null) {
                                    repeatthread = new Repeat();
                                    repeat = new Timer();
                                }
                                repeat.schedule(repeatthread, 0, 30 * 1000);
                                System.out.println("?????");
                            } else if (subject.equals("list") || subject.equals("List")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 4);
                            } else if (subject.equals("help") || subject.equals("Help")
                                    || subject.equals("")) {
                                Send(addrfrom.getAddress(), 5);
                            } else {
                                if (!Mailsocketchat.push && !Mailsocketchat.repeat) {
                                    Send(addrfrom.getAddress(), 0);
                                } else if (comment.equals("") || comment.equals(" ") || comment.equals("  ")) {
                                    Send(addrfrom.getAddress(), 5);
                                }
                            }
                        } catch (IOException ioex) {
                            System.out.println(
                                    "??????????");
                        } catch (MessagingException mex) {
                            System.out.println(
                                    "??????????");
                        }
                    }
                }
            });

            // Check mail once in "freq" MILLIseconds
            int freq = 1000; //??
            boolean supportsIdle = false;
            try {
                if (folder instanceof IMAPFolder) {
                    IMAPFolder f = (IMAPFolder) folder;
                    f.idle();
                    supportsIdle = true;
                }
            } catch (FolderClosedException fex) {
                throw fex;
            } catch (MessagingException mex) {
                supportsIdle = false;
            }
            for (;;) {
                if (supportsIdle && folder instanceof IMAPFolder) {
                    IMAPFolder f = (IMAPFolder) folder;
                    f.idle();
                } else {
                    Thread.sleep(freq); // sleep for freq milliseconds

                    // This is to force the IMAP server to send us
                    // EXISTS notifications. 
                    folder.getMessageCount();
                }
            }

        } catch (Exception ex) {
            System.out.println("??????????");
        }
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Removes Star Flag of a given Starred {@link GmailMessage}.
 *
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if unable to remove star flag from {@link GmailMessage}
 *//*from  w ww .j a va2s.  c o m*/
public void removeStar(int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid " + "GmailMessage number");
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(ImapGmailLabel.STARRED.getName(), store);
        folder.open(Folder.READ_WRITE);
        Message message = folder.getMessage(messageNumber);
        if (message.isSet(Flags.Flag.FLAGGED)) {
            message.setFlag(Flags.Flag.FLAGGED, false);
        }
    } catch (Exception e) {
        throw new GmailException(
                "ImapGmailClient failed removing" + " GmailMessage star flag : " + messageNumber, e);
    } finally {
        closeFolder(folder);
    }
}

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

public void getMessage(cfImapConnection imapConnection, String rootFolder, long messageID, String _attachURI,
        String _attachDIR) throws cfmRunTimeException {
    try {/* w w  w  .j a v  a  2 s .c  o  m*/
        Folder folderToList;

        if (rootFolder == null || rootFolder.length() == 0)
            folderToList = imapConnection.mailStore.getDefaultFolder();
        else
            folderToList = imapConnection.mailStore.getFolder(rootFolder);

        if ((folderToList.getType() & Folder.HOLDS_MESSAGES) != 0) {

            if (!folderToList.isOpen())
                folderToList.open(Folder.READ_ONLY);

            boolean bResult = false;
            if (folderToList instanceof UIDFolder)
                bResult = extractMessage(((UIDFolder) folderToList).getMessageByUID(messageID), messageID,
                        _attachURI, _attachDIR);
            else
                bResult = extractMessage(folderToList.getMessage((int) messageID), messageID, _attachURI,
                        _attachDIR);

            if (!bResult)
                imapConnection.setStatus(false, "Message does not exist");
            else
                imapConnection.setStatus(true, "");

            folderToList.close(false);
        }

    } catch (Exception E) {
        imapConnection.setStatus(false, E.getMessage());
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Move {@link GmailMessage} to a given destination folder.
 *
 * @param destFolder the destination {@link Folder} name.See {@see ImapGmailLabel}
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if it fails to move {@link GmailMessage} to the
 * destination folder/*from w  w w.  java 2 s .  c o  m*/
 */
public void moveTo(ImapGmailLabel destFolder, int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid GmailMessage number");
    }

    Folder fromFolder = null;
    Folder toFolder = null;

    try {
        final Store store = openGmailStore();
        fromFolder = getFolder(this.srcFolder, store);
        fromFolder.open(Folder.READ_WRITE);
        Message message = fromFolder.getMessage(messageNumber);

        if (message != null) {
            toFolder = getFolder(destFolder.getName(), store);

            if (fromFolder.getURLName().equals(toFolder.getURLName())) {
                throw new GmailException("ImapGmailClient cannot move " + "GmailMessage within same folder "
                        + "(from " + fromFolder.getFullName() + " to " + toFolder.getFullName() + ")");
            }
            // copy from source folder to destination folder
            fromFolder.copyMessages(new Message[] { message }, toFolder);
            // move the copied message to trash folder
            moveToTrash(new GmailMessage[] { new JavaMailGmailMessage(message) });
        }
    } catch (GmailException ge) {
        throw ge;
    } catch (Exception e) {
        throw new GmailException(
                "ImapGmailClient failed moving" + " GmailMessage from " + fromFolder.getFullName(), e);
    } finally {
        closeFolder(fromFolder);
    }
}

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Moves given {@link GmailMessage}'s to {@link ImapGmailLabel.TRASH} folder.
 *
 * @param gmailMessages {@link GmailMessage} message(s)
 * @throws GmailException if unable to move {@link GmailMessage}'s to
 * the Trash Folder/*from   w ww . j a v  a  2  s.  c om*/
 */
public void moveToTrash(final GmailMessage[] gmailMessages) {
    if (gmailMessages == null || gmailMessages.length <= 0) {
        LOG.warn("ImapGmailClient requires GmailMessage(s) to move" + " to move messages to trash folder");
        return;
    }
    Folder folder = null;

    try {
        final Store store = openGmailStore();
        folder = getFolder(this.srcFolder, store);
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        List<Message> markedMsgList = new ArrayList<Message>();
        for (GmailMessage gmailMessage : gmailMessages) {
            // get only messages that match to the specified message number
            Message message = folder.getMessage(gmailMessage.getMessageNumber());
            message.setFlag(Flags.Flag.SEEN, true);
            // mark message as delete
            message.setFlag(Flags.Flag.DELETED, true);
            markedMsgList.add(message);
        }

        Folder trash = getFolder(ImapGmailLabel.TRASH.getName(), store);
        if (folder.getURLName().equals(trash.getURLName())) {
            LOG.warn("ImapGmailClient trying to move GmailMessage(s) within"
                    + " same folder(ImapGmailLabel.TRASH.getName())");
        }
        // move the marked messages to trash folder
        if (!markedMsgList.isEmpty()) {
            folder.copyMessages(markedMsgList.toArray(new Message[0]), trash);
        }
    } catch (Exception e) {
        throw new GmailException("ImapGmailClient failed moving GmailMessage(s)" + " to trash folder: " + e);
    } finally {
        closeFolder(folder);
    }
}

From source file:com.silverpeas.mailinglist.service.job.TestZimbraConnection.java

@Test
public void testOpenImapConnection() {
    URL url = this.getClass().getClassLoader().getResource("truststore.jks");
    String path = url.getPath();/*w  ww.j ava2 s  .  c  o  m*/
    System.setProperty("javax.net.ssl.trustStore", path);
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    Store mailAccount = null;
    Folder inbox = null;
    Session mailSession = Session.getInstance(System.getProperties());
    try {
        mailSession.setDebug(true);
        mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol"));
        mailAccount.connect(props.getProperty("mail.server.host"),
                Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"),
                props.getProperty("mail.server.password"));
        inbox = mailAccount.getFolder("INBOX");
        if (inbox == null) {
            throw new MessagingException("No POP3 INBOX");
        }
        // -- Open the folder for read write --
        inbox.open(Folder.READ_WRITE);

        // -- Get the message wrappers and process them --
        Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
    } catch (MessagingException mex) {
        SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex);
    } catch (Exception mex) {
        SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", mex);
    } finally {
        // -- Close down nicely --
        try {
            if (inbox != null) {
                inbox.close(false);
            }
            if (mailAccount != null) {
                mailAccount.close();
            }
        } catch (Exception ex2) {
            SilverTrace.error("mailingList", "MessageChecker.checkNewMessages", "mail.processing.error", ex2);
        }
    }

}

From source file:com.silverpeas.mailinglist.service.job.TestYahooMailConnection.java

@Test
public void testOpenImapConnection() throws Exception {
    Store mailAccount = null;// ww  w .ja va 2s.c  o  m
    Folder inbox = null;
    Session mailSession = Session.getInstance(System.getProperties());
    try {
        mailSession.setDebug(true);
        mailAccount = mailSession.getStore(props.getProperty("mail.server.protocol"));
        mailAccount.connect(props.getProperty("mail.server.host"),
                Integer.parseInt(props.getProperty("mail.server.port")), props.getProperty("mail.server.login"),
                props.getProperty("mail.server.password"));
        inbox = mailAccount.getFolder("INBOX");
        if (inbox == null) {
            throw new MessagingException("No POP3 INBOX");
        }
        // -- Open the folder for read write --
        inbox.open(Folder.READ_WRITE);

        // -- Get the message wrappers and process them --
        javax.mail.Message[] msgs = inbox.getMessages();
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.FLAGS);
        inbox.fetch(msgs, profile);
        MailProcessor processor = new MailProcessor();
        MessageListener mailingList = mock(MessageListener.class);
        when(mailingList.checkSender(anyString())).thenReturn(Boolean.TRUE);
        when(mailingList.getComponentId()).thenReturn("mailingList38");
        MessageEvent event = new MessageEvent();
        for (javax.mail.Message message : msgs) {
            processor.prepareMessage((MimeMessage) message, mailingList, event);
        }
        assertThat(event.getMessages(), is(notNullValue()));
        assertThat(event.getMessages().size(), is(msgs.length));
        for (com.silverpeas.mailinglist.service.model.beans.Message message : event.getMessages()) {
            assertThat(message, is(notNullValue()));
            assertThat(message.getMessageId(), is(notNullValue()));
        }
    } finally {
        // -- Close down nicely --
        if (inbox != null) {
            inbox.close(false);
        }
        if (mailAccount != null) {
            mailAccount.close();
        }
    }
}