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:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*from   w w w.j a v a 2  s.c  om*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        try {
            if (!dst.create(src.getType())) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
        } catch (MessagingException mex) {
            // might not be able to create a folder that holds both
            if (src.getType() != (Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS))
                throw mex;
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:org.accesointeligente.server.robots.ResponseChecker.java

public void connectAndCheck() {
    if (ApplicationProperties.getProperty("email.server") == null
            || ApplicationProperties.getProperty("email.user") == null
            || ApplicationProperties.getProperty("email.password") == null
            || ApplicationProperties.getProperty("email.folder") == null
            || ApplicationProperties.getProperty("email.failfolder") == null
            || ApplicationProperties.getProperty("attachment.directory") == null
            || ApplicationProperties.getProperty("attachment.baseurl") == null) {
        logger.error("Properties are not defined!");
        return;//from  w  w w.j  a v a  2s .c  o  m
    }

    org.hibernate.Session hibernate = null;

    try {
        session = Session.getInstance(props, null);
        store = session.getStore("imaps");
        store.connect(ApplicationProperties.getProperty("email.server"),
                ApplicationProperties.getProperty("email.user"),
                ApplicationProperties.getProperty("email.password"));

        Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder"));
        Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder"));
        inbox.open(Folder.READ_WRITE);

        for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) {
            try {
                logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject());
                remoteIdentifiers = null;
                messageBody = null;
                remoteIdentifiers = new HashSet<String>();

                if (message.getSubject() != null) {
                    Matcher matcher = pattern.matcher(message.getSubject());

                    if (matcher.matches()) {
                        remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                        logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                    }
                }

                Object content = message.getContent();

                if (content instanceof Multipart) {
                    Multipart mp = (Multipart) message.getContent();
                    logger.info("Email content type is Multipart, each part of " + mp.getCount()
                            + " will be processed");

                    for (int i = 0, n = mp.getCount(); i < n; i++) {
                        Part part = mp.getBodyPart(i);
                        logger.info("Part: " + (i + 1) + " of " + mp.getCount());
                        processPart(part);
                    }
                } else if (content instanceof String) {
                    logger.info("Email content type is String");
                    messageBody = (String) content;
                    Matcher matcher;
                    StringTokenizer tokenizer = new StringTokenizer(messageBody);

                    while (tokenizer.hasMoreTokens()) {
                        String token = tokenizer.nextToken();
                        matcher = pattern.matcher(token);

                        if (matcher.matches()) {
                            remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                    Integer.parseInt(matcher.group(3))));
                            logger.info("remote identifier: " + formatIdentifier(matcher.group(1),
                                    matcher.group(2), Integer.parseInt(matcher.group(3))));
                        }
                    }
                } else {
                    logger.info("Email content type isn't String or Multipart");
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                    continue;
                }

                Boolean requestFound = false;
                Matcher matcher = htmlPattern.matcher(messageBody);

                if (matcher.find()) {
                    messageBody = htmlToString(messageBody);
                }

                logger.info("Searching for Request Remote Identifier");
                for (String remoteIdentifier : remoteIdentifiers) {
                    hibernate = HibernateUtil.getSession();
                    hibernate.beginTransaction();

                    Criteria criteria = hibernate.createCriteria(Request.class);
                    criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier));
                    Request request = (Request) criteria.uniqueResult();
                    hibernate.getTransaction().commit();

                    if (request != null) {
                        logger.info("Request found for Remote Identifier: " + remoteIdentifier);
                        Response response;

                        // If the attachments haven't been used, use them. Otherwise, copy them.
                        if (!requestFound) {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        } else {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        }

                        hibernate = HibernateUtil.getSession();
                        hibernate.beginTransaction();

                        response.setRequest(request);
                        request.setStatus(RequestStatus.RESPONDED);
                        request.setExpired(RequestExpireType.WITHRESPONSE);
                        request.setResponseDate(new Date());
                        hibernate.update(request);
                        hibernate.update(response);
                        hibernate.getTransaction().commit();
                        requestFound = true;
                    }
                }

                if (!requestFound) {
                    logger.info("Request not found");
                    createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(),
                            messageBody);
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                }
            } catch (Exception e) {
                if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
                    hibernate.getTransaction().rollback();
                }

                logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
            hibernate.getTransaction().rollback();
        }

        logger.error(e.getMessage(), e);
    }
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public int todosCorreosNum(String name) {
    int num = 0;/*from   ww  w .  ja  va2s  .  c o  m*/
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {
        users u = usuarioService.getByLogin(name);
        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);
        Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        System.out.println(" " + msg.length);
        num = msg.length;
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
    return num;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public int numCorreosNOL(String name) {
    int numMensa = 0;
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {//from  ww w .ja  v a2  s.c  o m
        users u = usuarioService.getByLogin(name);

        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);

        Message msg[] = inbox.search(ft);
        System.out.println("MAILS: " + msg.length);
        System.out.println(" " + msg.length);
        numMensa = msg.length;
    } catch (Exception ex) {
    }
    return numMensa;
}

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

/**
 * {@inheritDoc}/*from  w  ww  . ja va2  s  .  c  o m*/
 * 
 * @throws MessagingException
 * @throws
 * @throws Exception
 * @see org.xwiki.contrib.mail.IMailReader#read(java.lang.String, int, java.lang.String, java.lang.String,
 *      java.lang.String, java.lang.String, boolean, int)
 */
@Override
public Message read(final String folder, final String messageid) throws MessagingException {
    assert (getMailSource() != null);
    assert (getMailSource().getHostname() != null);

    Message message = null;
    store = null;
    boolean isGmail = getMailSource().getHostname() != null
            && getMailSource().getHostname().endsWith(".gmail.com");

    logger.info("Trying to retrieve mails from server " + getMailSource().getHostname());

    this.session = createSession(getMailSource().getProtocol(), getMailSource().getAdditionalProperties(),
            isGmail, getMailSource().isAutoTrustSSLCertificates());

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

    // Connect to the mail account
    store.connect(getMailSource().getHostname(), getMailSource().getPort(), getMailSource().getUsername(),
            getMailSource().getPassword());
    Folder fldr;
    // Specifically for GMAIL ...
    if (isGmail) {
        fldr = store.getDefaultFolder();
    }
    fldr = store.getFolder(folder);

    fldr.open(Folder.READ_WRITE);

    // Search with message id
    Message[] messages = fldr.search(new MessageIDTerm(messageid));

    if (messages.length > 0) {
        message = messages[0];
    }

    logger.info("Found message " + message);

    return message;
}

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

private Object getMessage(String requestMsgId) {
    Session session = Session.getInstance(props, null);
    session.setDebug(log.isTraceEnabled());
    Store store = null;//from   w  ww  . ja  v  a 2s .co m

    try {
        store = session.getStore("pop3");
        store.connect(username, password);
        Folder folder = store.getFolder(MailConstants.DEFAULT_FOLDER);
        folder.open(Folder.READ_WRITE);
        Message[] msgs = folder.getMessages();
        log.debug(msgs.length + " replies in reply mailbox");
        for (Message m : msgs) {
            String[] inReplyTo = m.getHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO);
            log.debug("Got reply to : " + Arrays.toString(inReplyTo));
            if (inReplyTo != null && inReplyTo.length > 0) {
                for (int j = 0; j < inReplyTo.length; j++) {
                    if (requestMsgId.equals(inReplyTo[j])) {
                        m.setFlag(Flags.Flag.DELETED, true);
                        return m.getContent();
                    }
                }
            }
            m.setFlag(Flags.Flag.DELETED, true);
        }
        folder.close(true);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (MessagingException ignore) {
            }
            store = null;
        }
    }
    return null;
}

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

/**
 * {@inheritDoc}//from  w w  w . j ava  2  s  . com
 * 
 * @throws MessagingException
 * @throws
 * @throws Exception
 * @see org.xwiki.contrib.mail.IMailReader#read(java.lang.String, int, java.lang.String, java.lang.String,
 *      java.lang.String, java.lang.String, boolean, int)
 */
@Override
public List<Message> read(final String folder, final boolean onlyUnread, final int max)
        throws MessagingException {
    assert (getMailSource() != null);
    assert (getMailSource().getHostname() != null);

    store = null;
    List<Message> messages = new ArrayList<Message>();
    boolean isGmail = getMailSource().getHostname() != null
            && getMailSource().getHostname().endsWith(".gmail.com");

    logger.info("Trying to retrieve mails from server " + getMailSource().getHostname());

    this.session = createSession(getMailSource().getProtocol(), getMailSource().getAdditionalProperties(),
            isGmail, getMailSource().isAutoTrustSSLCertificates());

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

    // Connect to the mail account
    store.connect(getMailSource().getHostname(), getMailSource().getPort(), getMailSource().getUsername(),
            getMailSource().getPassword());
    Folder fldr;
    // Specifically for GMAIL ...
    if (isGmail) {
        fldr = store.getDefaultFolder();
    }
    fldr = store.getFolder(folder);

    fldr.open(Folder.READ_WRITE);

    Message[] msgsArray;
    // Searches for mails not already read
    if (onlyUnread) {
        FlagTerm searchterms = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        msgsArray = fldr.search(searchterms);
    } else {
        msgsArray = fldr.getMessages();
    }

    if (max > 0 && msgsArray.length > max) {
        msgsArray = (Message[]) ArrayUtils.subarray(msgsArray, 0, max);
    }
    messages = new ArrayList<Message>(Arrays.asList(msgsArray));

    logger.info("Found " + messages.size() + " messages");

    // Note: we leave the Store opened to allow reading returned Messages

    return messages;
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

@RequestMapping(value = "/EajaxtestNoL", method = RequestMethod.GET)
public @ResponseBody String ajaxtestNoL(Principal principal) {
    String name = principal.getName();
    String result = "";
    try {/*w  w w  .  j av a2 s.c o m*/
        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:com.intranet.intr.inbox.EmpControllerInbox.java

public correoNoLeidos ltaRecibidos2(String name, int num) {
    correoNoLeidos lta = new correoNoLeidos();
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {/*  w  w w  .  ja v  a  2 s. c o m*/
        users u = usuarioService.getByLogin(name);
        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);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                if (num == message.getMessageNumber()) {
                    //message.setFlag(Flags.Flag.SEEN, true);
                    lta.setNum(message.getMessageNumber());
                    lta.setFecha(message.getSentDate().toString());
                    lta.setDe(message.getFrom()[0].toString());
                    lta.setAsunto(message.getSubject().toString());
                    correoNoLeidos co = new correoNoLeidos();
                    List<String> arc = new ArrayList<String>();
                    List<String> rar = new ArrayList<String>();
                    correoNoLeidos cc = analizaParteDeMensaje2(co, arc, rar, message);
                    lta.setImagenes(cc.getImagenes());
                    lta.setRar(cc.getRar());
                    lta.setContenido(cc.getContenido());
                    String cont = "";

                    String contenido = "";

                    //lta.setContenido(analizaParteDeMensaje2(message));
                }
            } catch (Exception e) {
                System.out.println("No Information");
            }

        }
    } catch (MessagingException e) {
        System.out.println(e.toString());
    }

    return lta;
}

From source file:gmailclientfx.controllers.SpamController.java

public void fetchSpam() {
    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"));

    spamTable.setItems(data);/*w  w w.  j  a va  2  s  .  co  m*/
    spamTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = spamTable.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));
                    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());
                    stage.show();
                } 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 spam = null;
        Folder[] folders = store.getDefaultFolder().list("*");
        for (Folder f : folders) {
            IMAPFolder imapFolder = (IMAPFolder) f;
            for (String att : imapFolder.getAttributes()) {
                if ("\\Junk".equals(att)) {
                    spam = f;
                }
            }
        }
        spam.open(Folder.READ_WRITE);

        MimeMessage[] seenMessages = (MimeMessage[]) spam
                .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, "SPAM");
            data.add(msg);
        }
        MimeMessage[] unseenMessages = (MimeMessage[]) spam
                .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, "SPAM");
            data.add(msg);
        }
        spam.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(SpamController.class.getName()).log(Level.SEVERE, null, ex);
    }
}