⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 imap4.java

📁 手机邮箱撒的方式方式方式的
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
            }
            reply = execute("LOGIN " + '"' + account.getUserName() + '"' + " " + '"' + account.getPassword() + '"', true);
            if (!reply.startsWith("OK")) {
                getReportBox().report("100: " + Lang.get(Lang.PL_NOTAUTHORIZED), SOURCE_FILE);
                return false;
            }

            if (task != null) { task.setTitle(Lang.get(Lang.ALRT_PL_CONNECTING) + account.getEmail() + Lang.get(Lang.SUCCESS)); }
            if (getTargetBox() != null && !getTargetBox().isPushActive()){
                connectionKeeper = new Timer();
                connectionKeeper.scheduleAtFixedRate(new Keeper(), Settings.noopIMAPPeriod, Settings.noopIMAPPeriod);
            }

            //#ifdef MUJMAIL_COMPRESSED_CONNECTION
            //if (isMujMailServer)
                //((ConnectionCompressed)connection).changeCompression( ConnectionCompressed.COMPRESSION_TYPE_GZIP);
            //#endif
            return true;

        } catch (MyException e) {
            e.printStackTrace();
            if (task != null) { task.setTitle(Lang.get(Lang.ALRT_PL_CONNECTING) + account.getEmail() + Lang.get(Lang.FAILED)); }
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            if (task != null) { task.setTitle(Lang.get(Lang.ALRT_PL_CONNECTING) + account.getEmail() + Lang.get(Lang.FAILED)); }
            e.printStackTrace();
            throw new MyException(MyException.COM_UNKNOWN, "100: " + e);
        }
    }

    private boolean selectMailBox(String box) throws MyException {
        String tag = execute("SELECT \"" + box + "\"", false);
        sld_mailBox_uidval = null; //SELECT automatically deselects currently selected mailbox
        String reply, uidvalidity = "";
        while (!(reply = connection.getLine()).startsWith(tag)) {
            if (reply.indexOf("[UIDVALIDITY") != -1) {
                uidvalidity = reply.substring(reply.indexOf("[UIDVALIDITY") + 13).trim();
                uidvalidity = uidvalidity.substring(0, uidvalidity.indexOf(']')).trim();
            }
        }
        if (reply.startsWith(tag + "OK")) {
            sld_mailBox_uidval = box + MessageHeader.MSG_ID_SEPARATOR_STR + uidvalidity + MessageHeader.MSG_ID_SEPARATOR_STR;
            return true;
        }
        return false;
    }

        // Note task can be null (background Keeper task)
    protected synchronized void _close(BackgroundTask task, boolean waitForReply) {
        if (!connection.isConnected()) {
            return;
        }
        if (task != null) { task.setTitle(Lang.get(Lang.ALRT_PL_CLOSING) + account.getEmail()); }
        if (connectionKeeper != null) {
            connectionKeeper.cancel();
        }
        connectionKeeper = null;
        forcedDisc = false;
        sld_mailBox_uidval = null;
        try {
            execute("CLOSE", waitForReply);
            execute("LOGOUT", waitForReply);
        } catch (MyException e) {
            if (task != null) { task.setTitle(Lang.get(Lang.ALRT_PL_CLOSING) + account.getEmail() + ": " + e.getDetails()); }
        }
        try {
            connection.close();
        } catch (Exception e) {
            if (task != null) { task.setTitle(Lang.get(Lang.ALRT_PL_CLOSING) + account.getEmail() + ": " + e); }
        }
        isMujMailServer = false;
        if (task != null) { task.setTitle(Lang.get(Lang.ALRT_PL_CLOSING) + account.getEmail() + Lang.get(Lang.SUCCESS)); }
    }

    protected void findFirstNewMailWhilePolling() throws MyException {
        Vector newMails = searchMailsMatching("UNSEEN");
        for (int i = newMails.size(); i > 0; --i) {
            String ID = (String) newMails.elementAt(i - 1);
            if (handleMailDiscoveredByPolling(ID)) break;
        }
    }

    protected void getNewMails() {
        // TODO: data overheads when we want to receive only X new mails?
        // check out countNew(), while (actual < max) {...} and
        //  while (actual > 0) {..}
        // the same is in POP3

        try {
            long startTime = System.currentTimeMillis();
              if (DEBUG) { System.out.println("STARTING GET_NEW_MAILS"); }
            if (!open(inProtocolTask)) { //in case of server->inbox sync we need to notify about this error
                //otherwise the synchronization will think that no mails are on the server
                //throw new MyException(MyException.PROTOCOL_CANNOT_CONNECT);
            	return;
            }
              if (DEBUG) { System.out.println("OPEN FINISHED"); }
            if (getTargetBox().isSyncRunning()) {
                mailsOnServer.clear();
            }//we need to recreate a new mailsOnServer lists
            //if its server->inbox sync is called then we want all mails
            //otherwise we just want to check new mails
            String criterium = getTargetBox().isSyncRunning() ? "ALL" : "UNSEEN";
            inProtocolTask.setTitle(Lang.get(Lang.ALRT_INPL_CHECK_MAILS) + account.getEmail());
            MessageHeader header;
            String mailBoxes = account.getIMAPPprimaryBox();
            if (!mailBoxes.endsWith(",")) {
                mailBoxes += ",";
            }

            Vector tempStorage = new Vector();
            while (mailBoxes.length() != 0) {
                //choose next mailbox
                String sld_box = mailBoxes.substring(0, mailBoxes.indexOf(','));
                //define what's the next mailbox
                mailBoxes = mailBoxes.substring(sld_box.length() + 1);
                //if selecting a mailbox is unsuccessful skip to the next one
                if (!selectMailBox(sld_box)) {
                	inProtocolTask.setTitle(Lang.get(Lang.ALRT_PL_CONNECTING) + account.getEmail() + ": " + sld_box + Lang.get(Lang.FAILED));
                    continue;
                }
                Vector newMails = new Vector();
                Vector fetchTags = new Vector();
                String fetchTag;
                //let's find UIDs of mails
                Vector tmp = searchMailsMatching(criterium);
                for (int i = 0; i < tmp.size(); ++i) {

                	if (!targetBox.isSyncRunning() &&
                		Settings.maxMailsRetrieve > 0 && i >= Settings.maxMailsRetrieve) //limit exceeded
                    {
                        break;
                    }

                    header = new MessageHeader(getTargetBox());
                    header.setMessageID(sld_mailBox_uidval + tmp.elementAt(i));
                    header.setIMAPFolder(sld_box);
                    newMails.addElement(header); //mark it to potentially new mails

                    if (inProtocolTask.stopped()) {
                    	_close(inProtocolTask, false);
                        return;
                    }
                }
                /* Memory management */
                tmp = null;
                System.gc();
                
                int n = 0;
                inProtocolTask.updateProgress(newMails.size(), 0);
                //for all potentially new mails, the newest first
                for (int actual = newMails.size() - 1; actual >= 0; --actual) {
                    header = (MessageHeader) newMails.elementAt(actual);
                    //let's remember that this mail is stored on the server
                    mailsOnServer.put(header.getMessageID(), String.valueOf(actual));
                    getTargetBox().newMailOnServer(); //increase synchronization counter

                    if (!targetBox.wasOnceDownloaded(account.getEmail(), header.getMessageID())) {
                        fetchTag = execute("UID FETCH " + parseUID(header.getMessageID()) + " (RFC822.SIZE FLAGS)", false);
                        if (!Settings.downWholeMail || Settings.safeMode) {
                            execute("UID FETCH " + parseUID(header.getMessageID()) + " (RFC822.HEADER)", false);
                        } else {
                            execute("UID FETCH " + parseUID(header.getMessageID()) + " (RFC822)", false);
                        }
                        fetchTags.addElement(fetchTag);
                        ++n;
                        if (Settings.maxMailsRetrieve > 0 && n >= Settings.maxMailsRetrieve) //limit exceeded
                        {
                            break;
                        }
                    }
                    else {
                    	newMails.removeElementAt(actual);
                        inProtocolTask.incActual(1);
                    }

                    if (inProtocolTask.stopped()) {
                        break;
                    }

                }
                int j = fetchTags.size() - 1;
                n = newMails.size() - n; //we will parse only mails whose size and header were required
                for (int actual = newMails.size() - 1; actual >= n; --actual) { //now lets parse new mails' headers
                    header = (MessageHeader) newMails.elementAt(actual);
                    fetchTag = (String) fetchTags.elementAt(j--);
                    String line = "";
                    do {
                        //skip useless lines of previous iteration or of fetch response
                        //until we get tagged BAD or NO response or good UID response
                        line = connection.getLine();
                          if (DEBUG) System.out.println( "DEBUG IMAP4.getNewMails() - line: " + line ); 
                    } while (!(line.startsWith(fetchTag) || line.indexOf("UID " + parseUID(header.getMessageID())) != -1));
                    if (line.startsWith(fetchTag)) { //bad response
                    	inProtocolTask.setTitle(account.getEmail() + ": " + line);
                        continue;
                    }

                    //Check for '\Seen', '\Answered', '\Flagged' and '\Deleted' flags
                    flags = line.substring(line.indexOf("FLAGS (") + 7);
                    flags = flags.substring(0, flags.indexOf(")"));
                    handleFlags(header, flags);

                    int i = line.indexOf("RFC822.SIZE") + 12;
                    line = line.substring(i);
                    for (i = 0; i < line.length(); ++i) {
                        if ( !('0' <= line.charAt(i) && line.charAt(i) <= '9')) {
                            break;
                        }
                    }
                    final String headerSize = line.substring(0, i);
                    if (DEBUG) System.out.println( "DEBUG IMAP4.getNewMails() - header size: " + headerSize);
                    header.setSize( Integer.parseInt( headerSize ) );
                    parseHeaders(header);

                    if (Settings.downWholeMail && !Settings.safeMode) {
                    	inProtocolTask.setTitle(Lang.get(Lang.ALRT_INPL_DOWN_MAIL) + header.getSubject());
                        try {
                            parseBody(header, inProtocolTask);
                            inProtocolTask.setTitle(Lang.get(Lang.ALRT_INPL_DOWN_MAIL) + header.getSubject() + Lang.get(Lang.SUCCESS));
                        } catch (MyException me) {
                        	inProtocolTask.setTitle(Lang.get(Lang.ALRT_INPL_DOWN_MAIL) + header.getSubject() + " " + Lang.get(Lang.FAILED) + " " + me.getDetails());
                        }
                    }
                    try {
                        header.saveHeader();
                        //getBox().getMailDB().saveHeader(header);
                        //cache the mail so next time we can quickly recognize it as already downloaded
                        getTargetBox().addToOnceDownloaded(header);
                        //also mark this mail as checked
                        getTargetBox().addToMsgIDs(header);
                        tempStorage.addElement( header ); // store the mail to temporary storage
                        if (!header.wasRead()) {
                            getTargetBox().changeUnreadMails(1);
                        }
                    } catch (MyException exp) {
                        clear(header); //markAsDeleted partially downloaded bodies
                        inProtocolTask.setTitle(Lang.get(Lang.ALRT_SAVING) + header.getSubject() + " " + Lang.get(Lang.FAILED) + " " + exp.getDetails());
                        if (getTargetBox().isSyncRunning()) //something's gone wrong, now we have to stop sync
                        {
                            throw exp;
                        }
                    }

                    inProtocolTask.incActual(1);
                    if (inProtocolTask.stopped()) {
                        break;
                    }
                }

                if (inProtocolTask.stopped()) {
                	break;
                }
            }
            
            if (inProtocolTask.stopped()) {
            	_close(inProtocolTask, false);
            }

              if (DEBUG) System.out.println( "DEBUG GetMailsTask.doRunWork() - storing mails to the box: " + getTargetBox().getName() );

            // In case this method is called from serversSync() method
            // addMailsInStorageToVector() and setStorage() methods
            // have to be atomic, otherwise TheBox.storage can be
            // overwritten by the last thread running getNewMails() method
            synchronized (getTargetBox().getStorage()) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -