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.intranet.intr.inbox.SupControllerInbox.java

@RequestMapping(value = "/ajaxtestNoL", method = RequestMethod.GET)
public @ResponseBody String ajaxtestNoL(Principal principal) {
    String name = principal.getName();
    String result = "";
    try {/*www  .j a va 2  s. c om*/
        users u = usuarioService.getByLogin(name);

        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");

        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                /*System.out.println("DATE: "+message.getSentDate().toString());
                System.out.println("FROM: "+message.getFrom()[0].toString());            
                System.out.println("SUBJECT: "+message.getSubject().toString());
                System.out.println("CONTENT: "+message.getContent().toString());
                System.out.println("******************************************");
                */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>"
                        + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString()
                        + "</span>" +

                        message.getSubject().toString() + "</span>" +

                        "</span>" + "</a>" + "</li> ";
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("No Information");
            }
        }

    } catch (Exception ex) {
    }

    return result;
}

From source file:gmailclientfx.controllers.PoslaneController.java

public void fetchPoslane() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacTo.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    poslaneTable.setItems(data);/* w  w  w . j  a  v  a2  s .  c om*/
    poslaneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = poslaneTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });
    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);

        Folder poslane = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Sent".equals(att)) {
                    poslane = f;
                }
            }
        }
        poslane.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) poslane
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "SENT");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) poslane
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "SENT");
            data.add(msg);
        }
        poslane.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(PoslaneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:gmailclientfx.controllers.ObrisaneController.java

public void fetchObrisane() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacFrom.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    obrisaneTable.setItems(data);/*from w  w  w . jav  a  2 s.c om*/
    obrisaneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = obrisaneTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });
    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);

        Folder obrisane = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Trash".equals(att)) {
                    obrisane = f;
                }
            }
        }
        obrisane.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) obrisane
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "DELETED");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) obrisane
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "DELETED");
            data.add(msg);
        }
        obrisane.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(ObrisaneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:gmailclientfx.controllers.NedovrseneController.java

public void fetchNedovrsene() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacTo.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    nedovrseneTable.setItems(data);//from  www. java2  s  .c  o m
    nedovrseneTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = nedovrseneTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });

    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);

        Folder nedovrsene = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Drafts".equals(att)) {
                    nedovrsene = f;
                }
            }
        }
        nedovrsene.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) nedovrsene
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "DRAFT");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) nedovrsene
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "DRAFT");
            data.add(msg);
        }
        nedovrsene.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(NedovrseneController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * //w ww.  j a  va  2s .  c  om
 */
@Override
public List<IMessage> receive(boolean clear) {
    List<IMessage> result = new ArrayList<IMessage>();

    try {
        String user = properties.getProperty("pop3.login.user");
        String password = properties.getProperty("pop3.login.password");

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

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port"));
        pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port"));

        URLName url = new URLName("pop3", properties.getProperty("pop3.host"),
                Integer.valueOf(properties.getProperty("pop3.port")), "", user, password);

        Session session = Session.getInstance(pop3Props, null);
        Store store = new POP3SSLStore(session, url);
        store.connect();

        // Open the Folder
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX");

        if (folder == null) {
            throw new RuntimeException("Invalid folder INBOX");
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }

        int count = folder.getMessageCount();
        // Message numbers start at 1
        for (int i = 1; i <= count; i++) {
            // Get a message by its sequence number
            Message m = folder.getMessage(i);
            Address[] from = m.getFrom();
            String type = from[0].getType();

            IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m));

            result.add(message);

            // delete message ?
            if (clear)
                m.setFlag(Flags.Flag.DELETED, true);
        }

        // "true" actually deletes flagged messages from folder
        folder.close(clear);
        store.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.gcaldaemon.core.GmailEntry.java

public final GmailMessage[] receive(String title) throws Exception {

    // Open 'INBOX' folder
    Folder inbox = mailbox.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);
    Message[] messages = inbox.getMessages();
    if (messages == null || messages.length == 0) {
        return new GmailMessage[0];
    }/*from   w  w w. ja va2 s .com*/

    // Loop on messages
    LinkedList list = new LinkedList();
    for (int i = 0; i < messages.length; i++) {
        Message msg = messages[i];
        if (!msg.isSet(Flag.SEEN)) {
            String subject = msg.getSubject();
            if (title == null || title.length() == 0 || title.equals(subject)) {
                GmailMessage gm = new GmailMessage();
                Address[] from = msg.getFrom();
                msg.setFlag(Flag.SEEN, true);
                if (from == null || from.length == 0) {
                    continue;
                }
                gm.subject = subject;
                gm.from = from[0].toString();
                gm.memo = String.valueOf(msg.getContent());
                list.addLast(gm);
            }
        }
    }
    inbox.close(true);

    // Return the array of the messages
    GmailMessage[] array = new GmailMessage[list.size()];
    list.toArray(array);
    return array;
}

From source file:edu.stanford.muse.email.ImapPopEmailStore.java

/** returns # of messages in folder. -1 if folder cannot be opened.
 * connect should already have been called */
public Folder openFolderWithoutCount(Store store, String fname) throws MessagingException {
    Folder folder = null;

    if (fname == null)
        fname = "INBOX";

    folder = store.getDefaultFolder();/*  w  w w  . j  ava2  s  .c  om*/
    folder = folder.getFolder(fname);

    if (folder == null)
        throw new RuntimeException("Invalid folder: " + fname);

    log.info("Opening folder " + Util.blurKeepingExtension(fname) + " in r/o mode...");
    try {
        folder.open(Folder.READ_ONLY);
    } catch (MessagingException me) {
        return null;
    }
    return folder;
}

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

private Folder openFolder(cfSession _Session, Store popStore) throws cfmRunTimeException {
    try {/*w  w  w.  j av a 2  s  .  c o  m*/
        Folder folder = popStore.getDefaultFolder();
        Folder popFolder = folder.getFolder("INBOX");
        popFolder.open(Folder.READ_WRITE);
        return popFolder;
    } catch (Exception E) {
        throw newRunTimeException(E.getMessage());
    }
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private void doReceiveMessages() throws Exception {

    log.debug("Checking mail ");

    String host = Turbine.getConfiguration().getString("mail.pop3.host");
    String username = Turbine.getConfiguration().getString("mail.pop3.user");
    String password = Turbine.getConfiguration().getString("mail.pop3.password");

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-only
    folder.open(Folder.READ_WRITE);

    // Get attributes & flags for all messages
    ////from   www. ja va 2s . co  m
    Message[] messages = folder.getMessages();
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    fp.add(FetchProfile.Item.FLAGS);
    fp.add("X-Mailer");
    folder.fetch(messages, fp);

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

        log.debug("Retrieving message " + i);

        // Process each message
        //
        InboxEvent entry = new InboxEvent();
        Address fromAddress = new InternetAddress();
        String from = new String();
        String name = new String();
        String email = new String();
        String replyTo = new String();
        String subject = new String();
        String content = new String();
        Date sentDate = new Date();
        int emailformat = 10;

        Message m = messages[i];

        // and now, handle the content
        Object o = m.getContent();

        // find content type
        if (m.isMimeType("text/plain")) {
            content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>";
            emailformat = 10;
        } else if (m.isMimeType("text/html")) {
            content = (String) o;
            emailformat = 20;
        } else if (m.isMimeType("text/*")) {
            content = (String) o;
            emailformat = 30;
        } else if (m.isMimeType("multipart/alternative")) {
            try {
                content = handleAlternative(o, content);
                emailformat = 20;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else if (m.isMimeType("multipart/*")) {
            try {
                content = handleMulitipart(o, content, entry);
                emailformat = 40;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else {
            content = "Problem with the message format. Messssage has left on the email server.";
            emailformat = 50;
            log.debug("Could not handle properly");
        }

        email = ((InternetAddress) m.getFrom()[0]).getAddress();
        name = ((InternetAddress) m.getFrom()[0]).getPersonal();
        replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress();
        sentDate = m.getSentDate();
        subject = m.getSubject();

        log.debug("Got message " + email + " " + name + " " + subject + " " + content);

        Criteria contcrit = new Criteria();
        contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (ContactPeer.doSelect(contcrit).size() > 0) {
            log.debug("From known contact");
            Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0);
            entry.setCustomerId(myContact.getCustomerId());
            entry.setContactId(myContact.getContactId());
        } else {

            // find if customer exists
            Criteria criteria = new Criteria();
            criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL);
            if (CustomerPeer.doSelect(criteria).size() > 0) {
                log.debug("From known customer");
                Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0);
                entry.setCustomerId(myDistrib.getCustomerId());
            }

        }

        entry.setInboxEventCode(getTempCode());
        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setEmailFormat(emailformat);
        entry.setSubject(subject);
        entry.setSenderEmail(email);
        entry.setSenderName(name);
        entry.setSenderReplyTo(replyTo);
        entry.setSentTime(sentDate);
        entry.setBody(content);
        entry.setIssuedDate(new Date());
        entry.setCreatedBy("system");
        entry.setCreated(new Date());
        entry.setModifiedBy("system");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;
        } finally {
            log.debug("Succcessfully stored in db: " + success);
            if (!success)
                Transaction.safeRollback(conn);
        }

        if (emailformat != 50) {
            m.setFlag(Flags.Flag.DELETED, true);
        }
    }

    // Close pop3 connection
    folder.close(true);
    store.close();

}

From source file:org.apache.syncope.core.notification.NotificationTest.java

private boolean verifyMail(final String sender, final String subject) throws Exception {
    LOG.info("Waiting for notification to be sent...");
    try {/*from ww  w  . j  a  v a  2  s .com*/
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    boolean found = false;
    Session session = Session.getDefaultInstance(System.getProperties());
    Store store = session.getStore("pop3");
    store.connect(pop3Host, pop3Port, mailAddress, mailPassword);

    Folder inbox = store.getFolder("INBOX");
    assertNotNull(inbox);
    inbox.open(Folder.READ_WRITE);

    Message[] messages = inbox.getMessages();
    for (int i = 0; i < messages.length; i++) {
        if (sender.equals(messages[i].getFrom()[0].toString()) && subject.equals(messages[i].getSubject())) {
            found = true;
            messages[i].setFlag(Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();
    return found;
}