Example usage for javax.mail Store connect

List of usage examples for javax.mail Store connect

Introduction

In this page you can find the example usage for javax.mail Store connect.

Prototype

public synchronized void connect(String host, int port, String user, String password)
        throws MessagingException 

Source Link

Document

Similar to connect(host, user, password) except a specific port can be specified.

Usage

From source file:net.fenyo.mail4hotspot.service.MailManager.java

public static void main(String[] args) throws NoSuchProviderException, MessagingException {
    System.out.println("Salut");

    //      trustSSL();

    /*       final Properties props = new Properties();
           props.put("mail.smtp.host", "my-mail-server");
           props.put("mail.from", "me@example.com");
           javax.mail.Session session = javax.mail.Session.getInstance(props, null);
           try {// w  ww.ja  v a2s.c o m
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom();
      msg.setRecipients(Message.RecipientType.TO,
                        "you@example.com");
      msg.setSubject("JavaMail hello world example");
      msg.setSentDate(new Date());
      msg.setText("Hello, world!\n");
      Transport.send(msg);
              } catch (MessagingException mex) {
      System.out.println("send failed, exception: " + mex);
              }*/

    final Properties props = new Properties();

    //props.put("mail.host", "10.69.60.6");
    //props.put("mail.user", "fenyo");
    //props.put("mail.from", "fenyo@fenyo.net");
    //props.put("mail.transport.protocol", "smtps");

    //props.put("mail.store.protocol", "pop3s");

    // [javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc],
    // javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc],
    // javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc],
    // javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc],
    // javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc],
    // javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc]]
    // final Provider[] providers = session.getProviders();

    javax.mail.Session session = javax.mail.Session.getInstance(props, null);

    session.setDebug(true);
    //session.setDebug(false);

    //       final Store store = session.getStore("pop3s");
    //       store.connect("10.69.60.6", 995, "fenyo", "PASSWORD");
    //       final Store store = session.getStore("imaps");
    //       store.connect("10.69.60.6", 993, "fenyo", "PASSWORD");
    //       System.out.println(store.getDefaultFolder().getMessageCount());

    //final Store store = session.getStore("pop3");
    final Store store = session.getStore("pop3s");
    //final Store store = session.getStore("imaps");

    //       store.addStoreListener(new StoreListener() {
    //          public void notification(StoreEvent e) {
    //          String s;
    //          if (e.getMessageType() == StoreEvent.ALERT)
    //          s = "ALERT: ";
    //          else
    //          s = "NOTICE: ";
    //          System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX: " + s + e.getMessage());
    //          }
    //       });

    //store.connect("10.69.60.6", 110, "fenyo", "PASSWORD");
    store.connect("pop.gmail.com", 995, "alexandre.fenyo@gmail.com", "PASSWORD");
    //store.connect("localhost", 110, "alexandre.fenyo@yahoo.com", "PASSWORD");
    //store.connect("localhost", 995, "fenyo@live.fr", "PASSWORD");
    //store.connect("localhost", 995, "thisisatestforalex@aol.fr", "PASSWORD");

    //       final Folder[] folders = store.getPersonalNamespaces();
    //       for (Folder f : folders) {
    //          System.out.println("Folder: " + f.getMessageCount());
    //          final Folder g = f.getFolder("INBOX");
    //          g.open(Folder.READ_ONLY);
    //          System.out.println("   g:" + g.getMessageCount());
    //       }

    final Folder inbox = store.getDefaultFolder().getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    System.out.println("nmessages: " + inbox.getMessageCount());

    final Message[] messages = inbox.getMessages();

    for (Message message : messages) {
        System.out.println("message:");
        System.out.println("  size: " + message.getSize());
        try {
            if (message.getFrom() != null)
                System.out.println("  From: " + message.getFrom()[0]);
        } catch (final Exception ex) {
            System.out.println(ex.toString());
        }
        System.out.println("  content-type: " + message.getContentType());
        System.out.println("  disposition: " + message.getDisposition());
        System.out.println("  description: " + message.getDescription());
        System.out.println("  filename: " + message.getFileName());
        System.out.println("  line count: " + message.getLineCount());
        System.out.println("  message number: " + message.getMessageNumber());
        System.out.println("  subject: " + message.getSubject());
        try {
            if (message.getAllRecipients() != null)
                for (Address address : message.getAllRecipients())
                    System.out.println("  address: " + address);
        } catch (final Exception ex) {
            System.out.println(ex.toString());
        }
    }

    for (Message message : messages) {
        System.out.println("-----------------------------------------------------");
        Object content;
        try {
            content = message.getContent();
            if (javax.mail.Multipart.class.isInstance(content)) {
                System.out.println("CONTENT OBJECT CLASS: MULTIPART");
                final javax.mail.Multipart multipart = (javax.mail.Multipart) content;
                System.out.println("multipart content type: " + multipart.getContentType());
                System.out.println("multipart count: " + multipart.getCount());
                for (int i = 0; i < multipart.getCount(); i++) {
                    System.out.println("  multipart body[" + i + "]: " + multipart.getBodyPart(i));
                    BodyPart part = multipart.getBodyPart(i);
                    System.out.println("    content-type: " + part.getContentType());
                }

            } else if (String.class.isInstance(content)) {
                System.out.println("CONTENT IS A STRING: {" + content + "}");
            } else {
                System.out.println("CONTENT OBJECT CLASS: " + content.getClass().toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    store.close();

}

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

public static Pair<Boolean, String> run() {
    PrintStream savedOut = System.out;
    InputStream savedIn = System.in;

    try {/*from w  ww.j ava 2s .co m*/
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(true);
        String filename = System.getProperty("java.io.tmpdir") + File.separatorChar + "verifyEmailSetup";
        PrintStream ps = new PrintStream(new FileOutputStream(filename));
        System.setOut(ps);
        System.setErr(ps);

        // Get a Store object
        Store store = null;
        store = session.getStore("imaps");
        store.connect("imap.gmail.com", 993, "checkmuse", ""); // not the real password. unfortunately, the checkmuse a/c will get blocked by google.
        //           Folder folder = store.getFolder("[Gmail]/Sent Mail");
        //           int totalMessages = folder.getMessageCount();
        // System.err.println (totalMessages + " messages!");
        ps.close();
        String contents = Util.getFileContents(filename);
        System.out.println(contents);
        return new Pair<Boolean, String>(Boolean.TRUE, contents);
    } catch (AuthenticationFailedException e) {
        /* its ok if auth failed. we only want to check if IMAPS network route is blocked.
         when network is blocked, we'll get something like
        javax.mail.MessagingException: No route to host; 
        nested exception is: 
        java.net.NoRouteToHostException: No route to host 
        ...
        */
        log.info("Verification succeeded: " + Util.stackTrace(e));
        return new Pair<Boolean, String>(Boolean.TRUE, "");
    } catch (Exception e) {
        log.warn("Verification failed: " + Util.stackTrace(e));
        return new Pair<Boolean, String>(Boolean.FALSE, e.toString()); // stack track reveals too much about our code... Util.stackTrace(e));         
    } finally {
        System.setOut(savedOut);
        System.setIn(savedIn);
    }
}

From source file:org.apache.juddi.v3.tck.UDDI_090_Smtp_ExternalTest.java

/**
 * gets all current messages from the mail server and returns the number
 * of messages containing the string, messages containing the string are
 * deleted from the mail server String is the body of each message
 *
 * @return number of matching and deleted messages
 * @param contains a string to search for
 */// ww  w  .j  a va 2s.c  o m
private static int fetchMail(String contains) {

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

    /* Set the mail properties */
    Properties properties = TckPublisher.getProperties();
    // Set manual Properties

    int found = 0;
    Session session = Session.getDefaultInstance(properties, null);
    Store store = null;
    try {
        store = session.getStore("pop3");

        store.connect(properties.getProperty("mail.pop3.host"),
                Integer.parseInt(properties.getProperty("mail.pop3.port", "110")),
                properties.getProperty("mail.pop3.username"), properties.getProperty("mail.pop3.password"));
        /* Mention the folder name which you want to read. */
        // inbox = store.getDefaultFolder();
        // inbox = inbox.getFolder("INBOX");
        Folder inbox = store.getFolder("INBOX");

        /* Open the inbox using store. */
        inbox.open(Folder.READ_WRITE);

        Message messages[] = inbox.getMessages();

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

            MimeMessageParser p = new MimeMessageParser(new MimeMessage(session, messages[i].getInputStream()));
            Enumeration allHeaders = p.getMimeMessage().getAllHeaders();
            while (allHeaders.hasMoreElements()) {
                Object j = allHeaders.nextElement();
                if (j instanceof javax.mail.Header) {
                    javax.mail.Header msg = (javax.mail.Header) j;
                    logger.info("XML as message header is " + msg.getValue());
                    if (msg.getValue().contains(contains)) {
                        //found it
                        messages[i].setFlag(Flags.Flag.DELETED, true);
                        found++;
                    }
                }
            }
            for (int k = 0; k < p.getAttachmentList().size(); k++) {
                InputStream is = p.getAttachmentList().get((k)).getInputStream();
                QuotedPrintableCodec qp = new QuotedPrintableCodec();
                // If "is" is not already buffered, wrap a BufferedInputStream
                // around it.
                if (!(is instanceof BufferedInputStream)) {
                    is = new BufferedInputStream(is);
                }
                int c;
                StringBuilder sb = new StringBuilder();
                System.out.println("Message : ");
                while ((c = is.read()) != -1) {
                    sb.append(c);
                    System.out.write(c);
                }
                is.close();
                String decoded = qp.decode(sb.toString());
                logger.info("decode message is " + decoded);
                if (decoded.contains(contains)) {
                    //found it
                    messages[i].setFlag(Flags.Flag.DELETED, true);
                    found++;
                }
            }

        }
        inbox.close(true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (Exception ex) {
            }
        }
    }
    return found;
}

From source file:com.email.ReceiveEmail.java

/**
 * This account fetches emails from a specified account and marks the emails
 * as seen, only touches the email account does not delete or move any
 * information./* ww w  . j a  v a  2s.co  m*/
 *
 * @param account SystemEmailModel
 */
public static void fetchEmail(SystemEmailModel account) {
    Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
    Properties properties = EmailProperties.setEmailInProperties(account);

    try {
        Session session = Session.getInstance(properties, auth);
        Store store = session.getStore();
        store.connect(account.getIncomingURL(), account.getIncomingPort(), account.getUsername(),
                account.getPassword());
        Folder fetchFolder = store.getFolder(account.getIncomingFolder());
        if (account.getIncomingFolder().trim().equals("")) {
            fetchFolder = store.getFolder("INBOX");
        }

        if (fetchFolder.exists()) {
            fetchFolder.open(Folder.READ_WRITE);
            Message[] msgs = fetchFolder.getMessages();

            // USE THIS FOR UNSEEN MAIL TO SEEN MAIL
            //Flags seen = new Flags(Flags.Flag.SEEN);
            //FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            //Message[] msgs = fetchFolder.search(unseenFlagTerm);
            //fetchFolder.setFlags(msgs, seen, true);
            if (msgs.length > 0) {
                List<String> messageList = new ArrayList<>();

                for (Message msg : msgs) {
                    boolean notDuplicate = true;
                    String headerText = Arrays.toString(msg.getHeader("Message-ID"));

                    for (String header : messageList) {
                        if (header.equals(headerText)) {
                            notDuplicate = false;
                            break;
                        }
                    }

                    if (notDuplicate) {
                        //Add to header to stop duplicates
                        messageList.add(headerText);
                        attachmentCount = 1;
                        attachmentList = new ArrayList<>();

                        //Setup Email For dbo.Email
                        EmailMessageModel eml = new EmailMessageModel();
                        String emailTime = String.valueOf(new Date().getTime());
                        eml.setSection(account.getSection());
                        eml = saveEnvelope(msg, msg, eml);
                        eml.setId(EMail.InsertEmail(eml));

                        //After Email has been inserted Gather Attachments
                        saveAttachments(msg, msg, eml);

                        //Create Email Body
                        eml = EmailBodyToPDF.createEmailBodyIn(eml, emailTime, attachmentList);

                        //Insert Email Body As Attachment (so it shows up in attachment table during Docketing)
                        EmailAttachment.insertEmailAttachment(eml.getId(), eml.getEmailBodyFileName());

                        //Flag email As ready to file so it is available in the docket tab of SERB3.0
                        eml.setReadyToFile(1);
                        EMail.setEmailReadyToFile(eml);
                    }

                    if (deleteEmailEnabled) {
                        //  Will Delete message from server
                        //  Un Comment line below to run
                        msg.setFlag(Flags.Flag.DELETED, true);
                    }
                }
            }
            fetchFolder.close(true);
            store.close();
        }
    } catch (MessagingException ex) {
        if (ex != null) {
            System.out.println("Unable to connect to email Server for: " + account.getEmailAddress()
                    + "\nPlease ensure you are connected to the network and" + " try again.");
        }
        ExceptionHandler.Handle(ex);
    }
}

From source file:ru.codemine.ccms.mail.EmailAttachmentExtractor.java

public void saveAllAttachment() {
    String protocol = ssl ? "imaps" : "imap";

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

    try {//from  w  w  w  .  java 2s.  c  o  m
        Session session = Session.getInstance(props);
        Store store = session.getStore();
        store.connect(host, port, username, password);

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

        for (Message msg : inbox.getMessages()) {
            if (!msg.isSet(Flags.Flag.SEEN)) {
                String fileNamePrefix = settingsService.getStorageEmailPath() + "msg-" + msg.getMessageNumber();
                Multipart multipart = (Multipart) msg.getContent();
                for (int i = 0; i < multipart.getCount(); i++) {
                    BodyPart bodyPart = multipart.getBodyPart(i);
                    if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && StringUtils.isNotEmpty(bodyPart.getFileName())) {
                        MimeBodyPart mimimi = (MimeBodyPart) bodyPart; // =(^.^)= 
                        mimimi.saveFile(fileNamePrefix + MimeUtility.decodeText(bodyPart.getFileName()));
                        msg.setFlag(Flags.Flag.SEEN, true);
                    }
                }
            }
        }
    } catch (IOException | MessagingException e) {
        log.error("? ? ?,  : "
                + e.getMessage());
    }

}

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

public Store connect() throws MessagingException {
    if (Util.nullOrEmpty(connectOptions.protocol)) // should be at least imap or pop
        return null;

    // Get a Session object
    // can customize javamail properties here, see e.g. http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/package-summary.html
    // login form will prepend the magic string xoauth, if oauth is being used
    String oauthToken = "";
    String OAUTH_MAGIC_STRING = "xoauth"; // defined in loginform
    if (connectOptions.password.startsWith(OAUTH_MAGIC_STRING)) {
        if ("xoauth".length() < connectOptions.password.length()) {
            oauthToken = connectOptions.password.substring(OAUTH_MAGIC_STRING.length());
            mstoreProps.put("mail.imaps.sasl.enable", "true");
            mstoreProps.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
            mstoreProps.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
            log.info("Using oauth login for store " + this);
        }//from www  .j a va 2s .com
    }

    session = Session.getInstance(mstoreProps, null);
    //   session.setDebug(DEBUG);
    Store st = session.getStore(connectOptions.protocol);
    st.connect(connectOptions.server, connectOptions.port, connectOptions.userName,
            Util.nullOrEmpty(oauthToken) ? connectOptions.password : ""); // no password if oauth
    this.store = st;
    return st;
}

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  .ja v  a  2 s .  co  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;
    Folder inbox = null;/*from   w w  w . ja  v  a2  s.  c o m*/
    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();
        }
    }
}

From source file:org.opennms.javamail.JavaReadMailer.java

/**
 * <p>retrieveMessages</p>/* ww  w  .java 2 s.  c o  m*/
 *
 * @param term a {@link javax.mail.search.SearchTerm} object.
 * @return a {@link java.util.List} object.
 * @throws org.opennms.javamail.JavaMailerException if any.
 */
public List<Message> retrieveMessages(SearchTerm term) throws JavaMailerException {
    Message[] msgs;
    Folder mailFolder = null;

    try {
        Store store = m_session.getStore(m_config.getReadmailHost().getReadmailProtocol().getTransport());
        store.connect(m_config.getReadmailHost().getHost(), (int) m_config.getReadmailHost().getPort(),
                m_config.getUserAuth().getUserName(), m_config.getUserAuth().getPassword());
        mailFolder = store.getFolder(m_config.getMailFolder());
        mailFolder.open(Folder.READ_WRITE);
        msgs = mailFolder.search(term);
    } catch (NoSuchProviderException e) {
        throw new JavaMailerException(
                "No provider matching:" + m_config.getReadmailHost().getReadmailProtocol().getTransport()
                        + " from config:" + m_config.getName(),
                e);
    } catch (MessagingException e) {
        throw new JavaMailerException("Problem reading messages from configured mail store", e);
    }

    List<Message> msgList = Arrays.asList(msgs);

    return msgList;
}

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

public void run() {
    while (true) {
        try {/*from www .  j av  a 2  s.  c  o  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("??????????");
        }
    }
}