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:gmailclientfx.controllers.InboxController.java

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

    Platform.runLater(() -> {// w  w  w.j a  v a 2 s. c  o  m
        inboxTable.setItems(data);
    });
    inboxTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = inboxTable.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 inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);
        int getSeenCount = inbox.getMessageCount();
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfileItem.FLAGS);
        fp.add(FetchProfileItem.CONTENT_INFO);
        fp.add("X-mailer");

        MimeMessage[] seenMessages = (MimeMessage[]) inbox
                .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, "INBOX");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) inbox
                .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, "INBOX");
            data.add(msg);
        }

        inbox.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:FolderModel.java

public void setFolder(Folder what) throws MessagingException {
    if (what != null) {

        // opened if needed
        if (!what.isOpen()) {
            what.open(Folder.READ_WRITE);
        }//w ww .  java 2s. c o m

        // get the messages
        messages = what.getMessages();
        cached = new String[messages.length][];
    } else {
        messages = null;
        cached = null;
    }
    // close previous folder and switch to new folder
    if (folder != null)
        folder.close(true);
    folder = what;
    fireTableDataChanged();
}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * Returns the number of messages on the server
 * /* w w  w  .j a v a 2 s . c  o  m*/
 * @param folderName
 * @return 
 * @throws MessagingException
 */
private Integer getMessageNumber(String folderName) throws MessagingException {
    // Get folder
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    Integer messageCount = folder.getMessageCount();

    folder.close(false);

    return messageCount;
}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

/**
 * {@inheritDoc}//from w  w  w  . j  a v  a2  s.  c o m
 * 
 * @throws MessagingException
 * @see org.xwiki.contrib.mail.IMailReader#readFromStore(java.lang.String)
 */
public Message read(String folder, String messageid) throws MessagingException {
    Store store = getJavamailStore();
    store.connect();

    Folder mailFolder = store.getDefaultFolder().getFolder(folder);
    mailFolder.open(Folder.READ_ONLY);
    Message[] messages = mailFolder.search(new MessageIDTerm(messageid));
    mailFolder.close(false);
    store.close();
    if (messages.length > 0) {
        return messages[0];
    }
    return null;
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

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

    try {/*from  ww w.  j a v a2 s .c  om*/
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

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

public void computeFoldersAndCounts(String cacheDir /*unused */) throws MessagingException {
    if (store == null)
        connect();//from  www . ja  va  2s . co m
    if (!store.isConnected())
        connect();

    doneReadingFolderCounts = false;
    this.folderInfos = new ArrayList<FolderInfo>();
    if ("pop3".equals(connectOptions.protocol) || "pop3s".equals(connectOptions.protocol)) {
        Folder f = store.getDefaultFolder();
        f = f.getFolder("INBOX");
        f.open(Folder.READ_ONLY);
        int count = f.getMessageCount();
        f.close(false);
        this.folderInfos.add(new FolderInfo(getAccountID(), "INBOX", "INBOX", count));
    } else
        collect_folder_names(store, this.folderInfos, store.getDefaultFolder());

    folderBeingScanned = "";

    if (connectOptions.server.endsWith(".pobox.stanford.edu"))
        this.folderInfos.add(new FolderInfo(getAccountID(), "INBOX", "INBOX", 0)); // hack for stanford imap, it lists INBOX as a dir folder! TOFIX

    doneReadingFolderCounts = true;
}

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

/**
 * Import messages/*from  w ww  .  j a  v  a 2 s .  c o m*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info("======= ======= {} ======= =======", i);
            log.info("Subject: {}", msg.getSubject());
            log.info("From: {}", msg.getFrom());
            log.info("Received: {}", msg.getReceivedDate());
            log.info("Sent: {}", msg.getSentDate());
            com.openkm.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

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

private void doReceiveMessages() throws Exception {

    String host = TurbineResources.getString("mail.pop3.host");
    String username = TurbineResources.getString("mail.pop3.user");
    String password = TurbineResources.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   w  w w .j  a  v  a2  s.c  o  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);

    // Process each message
    //
    Address fromAddress = new InternetAddress();
    String from = new String();
    String name = new String();
    String email = new String();
    String subject = new String();
    String content = new String();
    for (int i = 0; i < messages.length; i++) {
        email = ((InternetAddress) messages[i].getFrom()[0]).getAddress();
        name = ((InternetAddress) messages[i].getFrom()[0]).getPersonal();
        subject = messages[i].getSubject();
        content = messages[i].getContent().toString();

        DinboxEvent entry = new DinboxEvent();

        Criteria criteria = new Criteria();
        criteria.add(DistributorPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (DistributorPeer.doSelect(criteria).size() > 0) {
            Distributor myDistrib = (Distributor) DistributorPeer.doSelect(criteria).get(0);
            entry.setDistributorId(myDistrib.getDistributorId());
        } else {
            if (name != null) {
                entry.setBody("From: " + name + " " + email + "\n\n" + content);
            } else {
                entry.setBody("From: " + email + "\n\n" + content);
            }
        }

        entry.setDinboxEventCode(getTempCode());

        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setSubject(subject);

        entry.setIssuedDate(new Date());
        entry.setCreatedBy("scheduler");
        entry.setCreated(new Date());
        entry.setModifiedBy("scheduler");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(DinboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setDinboxEventCode(getRowCode("IE", entry.getDinboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;

        } finally {
            if (!success)
                Transaction.safeRollback(conn);
        }

        messages[i].setFlag(Flags.Flag.DELETED, true);
    }

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

}

From source file:org.usergrid.rest.management.RegistrationIT.java

private Message[] getMessages(String host, String user, String password)
        throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
        logger.info("Subject: " + m.getSubject());
        logger.info("Body content 0 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
        logger.info("Body content 1 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }/*from   w ww .j  a v  a  2  s.  c o m*/
    return msgs;
}

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword) throws IOException {

    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);//from  ww w . ja v a 2  s .c o m
    try {
        // connects to the message store
        Store store = session.getStore(mailStoreProtocol);
        store.connect(mailStoreHost, mailStoreUserName, mailStorePassword);

        logger.info("connected to message store");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t Message: " + messageContent);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}