posts - 0, comments - 77, trackbacks - 0, articles - 356
            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          Pop3Bean接收郵件

          Posted on 2007-08-21 08:55 semovy 閱讀(521) 評(píng)論(0)  編輯  收藏 所屬分類(lèi): JAVA應(yīng)用

          package com.semovy.test;

          //package com.IEthing.util;

          import java.io.BufferedReader;
          import java.io.BufferedWriter;
          import java.io.ByteArrayOutputStream;
          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileNotFoundException;
          import java.io.FileWriter;
          import java.io.IOException;
          import java.io.InputStream;
          import java.io.InputStreamReader;
          import java.io.Reader;
          import java.io.StringReader;
          import java.text.SimpleDateFormat;
          import java.util.Date;

          import javax.mail.BodyPart;
          import javax.mail.Flags;
          import javax.mail.Folder;
          import javax.mail.Message;
          import javax.mail.MessagingException;
          import javax.mail.Multipart;
          import javax.mail.Part;
          import javax.mail.Session;
          import javax.mail.Store;
          import javax.mail.internet.InternetAddress;
          import javax.mail.internet.MimeMessage;
          import javax.mail.internet.MimeUtility;

          /**
           * @author David update by tegger
           *
           * TODO To change the template for this generated type comment go to Window -
           * Preferences - Java - Code Style - Code Templates
           */
          public class Pop3Bean {

           private int mailCounter; // 郵件計(jì)數(shù)

           private int mailIndex; // 郵件編號(hào),即郵件在messages數(shù)組中的位置

           private int mailDownErrorCounter; // 正在下載郵件時(shí),出錯(cuò)的計(jì)數(shù)器

           private boolean[] recordFailure; // 記錄下載出錯(cuò)的郵件的序號(hào)

           private int totalRetryTimes; // 總共重試次數(shù)

           private int retryTimeCounter; // 記下重試的次數(shù)

           private boolean otherError; // 若是在郵件正式下載之前出錯(cuò),則置該值為true

           private String extension = ".eml"; // 文件擴(kuò)展名

           private Store store;

           private Folder folder;

           private Message[] messages;

           private Message message;

           private Part part;

           private String emlName;

           private String attachName;

           private int allMessageCount;

           private int messageCount;

           private String dateformat; // 默認(rèn)的日前顯示格式

           // private String propFile =
           // MailConstants.PROPS_FILE_NAME;//用這個(gè)接口類(lèi)的好處是更改配置文件路徑的時(shí)候不需要更改每個(gè)類(lèi)

           private String protocol = "pop3"; // 服務(wù)協(xié)議

           private String mailHost; // 服務(wù)器地址

           private String userName; // 用戶(hù)名

           private String password; // 密碼

           private String saveAttachPath; // 附件下載后的存放目錄

           private String saveEmlPath = "E:\\"; // 保存eml文件的路徑

           public Pop3Bean() throws IOException {
            /*
             * FileProperties fp = new FileProperties(propFile); fp.load(); protocol =
             * fp.getProperty(MailConstants.RECV_PROTO); mailHost =
             * fp.getProperty(MailConstants.RECV_HOST); userName =
             * fp.getProperty(MailConstants.RECV_USER); password =
             * fp.getProperty(MailConstants.RECV_PASS); saveAttachPath =
             * fp.getProperty(MailConstants.RECV_ATTACH); saveEmlPath =
             * fp.getProperty(MailConstants.RECV_ROOT); dateformat =
             * fp.getProperty("mail.receive.dtfmat"); extension =
             * fp.getProperty("mail.receive.extension"); totalRetryTimes = Integer
             * .parseInt(fp.getProperty("mail.receive.retry"));
             */
           }

           /**
            * 設(shè)置郵件主機(jī)
            */
           public void setMailHost(String mailHost) {
            this.mailHost = mailHost;
           }

           /**
            * 獲取郵件主機(jī)
            */
           public String getMailHost() {
            return this.mailHost;
           }

           /**
            * 設(shè)置郵件帳號(hào)
            */
           public void setUserName(String userName) {
            this.userName = userName;
           }

           /**
            * 獲取郵件帳號(hào)
            */
           public String getUserName() {
            return this.userName;
           }

           /**
            * 設(shè)置郵件密碼
            */
           public void setPassword(String password) {
            this.password = password;
           }

           /**
            * 設(shè)置Store
            */
           public void setStore(Store store) {
            this.store = store;
           }

           /**
            * 設(shè)置郵箱文件夾
            */
           public void setFolder(Folder folder) {
            this.folder = folder;
           }

           /**
            * 設(shè)置messages數(shù)組
            */
           public void setMessages(Message[] messages) {
            this.messages = messages;
           }

           /**
            * 設(shè)置message
            */
           public void setMessage(Message message) {
            this.message = message;
           }

           public void setCurMessage(int i) {
            this.message = this.messages[i];
           }

           /**
            * 獲取message
            */
           public Message getMessage() {
            return this.message;
           }

           /**
            * 獲取folder中的message數(shù)量
            *
            * @throws MessagingException
            */
           public int getAllMessageCount() throws MessagingException {
            this.allMessageCount = folder.getMessageCount();
            return allMessageCount;
           }

           /**
            * 設(shè)置allMessageCount
            *
            * @throws MessagingException
            */
           private void setAllMessageCount() throws MessagingException {
            this.allMessageCount = this.folder.getMessageCount();
           }

           /**
            * 獲取messages中message的數(shù)量
            *
            * @return
            */
           public int getMessageCount() {
            this.messageCount = this.messages.length;
            return messageCount;
           }

           /**
            * 獲得folder中新郵件的數(shù)量
            *
            * @return
            * @throws MessagingException
            */
           public int getNewMessageCount() throws MessagingException {
            return this.folder.getNewMessageCount();
           }

           /**
            * 獲得folder中未讀郵件的數(shù)量
            *
            * @return
            * @throws MessagingException
            */
           public int getUnreadMessageCount() throws MessagingException {
            return this.folder.getUnreadMessageCount();
           }

           /**
            * 獲取Part
            */
           public Part getPart() {
            return (Part) message;
           }

           /**
            * 設(shè)置Part
            */
           public void setPart(Part part) {
            this.part = part;
           }

           /**
            * 設(shè)置附件存放路徑
            */

           public void setAttachPath(String attachPath) {
            this.saveAttachPath = attachPath;
           }

           /**
            * 獲得附件存放路徑
            */

           public String getAttachPath() {
            return saveAttachPath;
           }

           /**
            * 設(shè)置eml存放路徑
            */

           public void setEmlPath(String emlPath) {
            this.saveEmlPath = emlPath;
           }

           /**
            * 獲得eml存放路徑
            */

           public String getEmlPath() {
            return saveEmlPath;
           }

           public void setEmlName(String emlName) {
            this.emlName = emlName;
           }

           public String getEmlName() {
            return emlName;
           }

           public void setAttachName(String attachName) {
            this.attachName = attachName;
           }

           public String getAttachName() {
            return attachName;
           }

           public void setExtension(String extension) {
            this.extension = extension;
           }

           public String getExtension() {
            return extension;
           }

           /**
            * 設(shè)置日期顯示格式
            */

           public void setDateFormat(String format) throws Exception {
            this.dateformat = format;
           }

           /**
            * 獲取日期顯示格式
            */
           public String getDateFormat(String format) throws Exception {
            return this.dateformat;
           }

           /**
            * 獲得發(fā)件人的地址和姓名
            *
            * @throws Exception
            */
           public String getFrom() throws Exception {
            return getFrom(this.message);
           }

           public String getFrom(Message mimeMessage) throws Exception {
            InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
            String from = address[0].getAddress();
            if (from == null)
             from = "";
            String personal = address[0].getPersonal();
            if (personal == null)
             personal = "";
            String fromaddr = personal + "<" + from + ">";
            return fromaddr;
           }

           /**
            * 獲得郵件的收件人,抄送,和密送的地址和姓名,根據(jù)所傳遞的參數(shù)的不同 * "to"----收件人 "cc"---抄送人地址
            * "bcc"---密送人地址
            */
           public String getTOAddress() throws Exception {
            return getMailAddress("TO", this.message);
           }

           public String getCCAddress() throws Exception {
            return getMailAddress("CC", this.message);
           }

           public String getBCCAddress() throws Exception {
            return getMailAddress("BCC", this.message);
           }

           public String getTOAddress(Message mimeMessage) throws Exception {
            return getMailAddress("TO", mimeMessage);
           }

           public String getCCAddress(Message mimeMessage) throws Exception {
            return getMailAddress("CC", mimeMessage);
           }

           public String getBCCAddress(Message mimeMessage) throws Exception {
            return getMailAddress("BCC", mimeMessage);
           }

           public String getMailAddress(String type) throws Exception {
            return getMailAddress(type, this.message);
           }

           public String getMailAddress(String type, Message mimeMessage)
             throws Exception {
            String mailaddr = "";
            String addtype = type.toUpperCase();
            InternetAddress[] address = null;
            if (addtype.equals("TO") || addtype.equals("CC")
              || addtype.equals("BCC")) {
             if (addtype.equals("TO")) {
              address = (InternetAddress[]) mimeMessage
                .getRecipients(Message.RecipientType.TO);
             } else if (addtype.equals("CC")) {
              address = (InternetAddress[]) mimeMessage
                .getRecipients(Message.RecipientType.CC);
             } else {
              address = (InternetAddress[]) mimeMessage
                .getRecipients(Message.RecipientType.BCC);
             }
             if (address != null) {
              for (int i = 0; i < address.length; i++) {
               String email = address[i].getAddress();
               if (email == null)
                email = "";
               else {
                email = MimeUtility.decodeText(email);
               }
               String personal = address[i].getPersonal();
               if (personal == null)
                personal = "";
               else {
                personal = MimeUtility.decodeText(personal);
               }
               String compositeto = personal + "<" + email + ">";
               mailaddr += "," + compositeto;
              }
              mailaddr = mailaddr.substring(1);
             }
            } else {
             throw new Exception("Error emailaddr type!");
            }
            return mailaddr;
           }

           /**
            * 獲得郵件主題
            */
           public String getSubject() throws MessagingException {
            return getSubject(this.message);
           }

           public String getSubject(Message mimeMessage) throws MessagingException {
            String subject = "";
            try {
             subject = MimeUtility.decodeText(mimeMessage.getSubject());
             if (subject == null)
              subject = "";
            } catch (Exception exce) {
            }
            return subject;
           }

           /**
            * 獲得郵件發(fā)送日期
            */
           public String getSentDate() throws Exception {
            return getSentDate(this.message);
           }

           public String getSentDate(Message mimeMessage) throws Exception {
            Date sentdate = mimeMessage.getSentDate();
            SimpleDateFormat format = new SimpleDateFormat(dateformat);
            return format.format(sentdate);
           }

           /**
            * 判斷此郵件是否需要回執(zhí),如果需要回執(zhí)返回"true",否則返回"false"
            */
           public boolean getReplySign() throws MessagingException {
            return getReplySign(this.message);
           }

           public boolean getReplySign(Message mimeMessage) throws MessagingException {
            boolean replysign = false;
            String needreply[] = mimeMessage
              .getHeader("Disposition-Notification-To");
            if (needreply != null) {
             replysign = true;
            }
            return replysign;
           }

           /**
            * 獲得此郵件的Message-ID
            */
           public String getMessageId() throws MessagingException {
            return getMessageId(this.message);
           }

           public String getMessageId(Message mimeMessage) throws MessagingException {
            return ((MimeMessage) mimeMessage).getMessageID();
           }

           /**
            * 初始化出錯(cuò)郵件數(shù)組
            *
            */
           private void setRecordFailure() {
            this.recordFailure = new boolean[getMessageCount()];
           }

           /**
            * 返回出錯(cuò)數(shù)組
            *
            * @return
            */
           public boolean[] getRecordFailure() {
            return this.recordFailure;
           }

           /**
            * 判斷此郵件是否已讀,如果未讀返回返回false,反之返回true
            */
           public boolean isNew() throws MessagingException {
            return isNew(this.message);
           }

           /**
            * 判斷此郵件是否已讀,如果未讀返回返回false,反之返回true
            */
           public boolean isNew(Message mimeMessage) throws MessagingException {
            boolean isnew = false;
            Flags flags = mimeMessage.getFlags();
            Flags.Flag[] flag = flags.getSystemFlags();
            for (int i = 0; i < flag.length; i++) {
             if (flag[i] == Flags.Flag.SEEN) {
              isnew = true;
              break;
             }
            }
            return isnew;
           }

           /**
            * 判斷此郵件是否包含附件
            */
           public boolean isContainAttach() throws Exception {
            return isContainAttach(this.part);
           }

           /**
            * 判斷此郵件是否包含附件
            */
           public boolean isContainAttach(Part part) throws Exception {
            boolean attachflag = false;
            String contentType = part.getContentType();
            if (part.isMimeType("multipart/*")) {
             Multipart mp = (Multipart) part.getContent();
             for (int i = 0; i < mp.getCount(); i++) {
              BodyPart mpart = mp.getBodyPart(i);
              String disposition = mpart.getDisposition();
              if ((disposition != null)
                && ((disposition.equals(Part.ATTACHMENT)) || (disposition
                  .equals(Part.INLINE))))
               attachflag = true;
              else if (mpart.isMimeType("multipart/*")) {
               attachflag = isContainAttach((Part) mpart);
              } else {
               String contype = mpart.getContentType();
               if (contype.toLowerCase().indexOf("application") != -1)
                attachflag = true;
               if (contype.toLowerCase().indexOf("name") != -1)
                attachflag = true;
              }
             }
            } else if (part.isMimeType("message/rfc822")) {
             attachflag = isContainAttach((Part) part.getContent());
            }
            return attachflag;
           }

           /**
            * 連到server,創(chuàng)建folder對(duì)象,創(chuàng)建message對(duì)象
            */
           public void getConn() {
            try {
             this.getStoreFromServer();
             this.getFolderFromStore();
            } catch (Exception e) {
             otherError = true;
             mailDownErrorCounter++;
             System.out.print(e.getLocalizedMessage());
            }
           }

           /**
            * 建立Store連接
            */
           private Store getStoreFromServer() throws Exception {
            // 創(chuàng)建session
            Session session = Session.getDefaultInstance(System.getProperties(),
              null);
            // session.setDebug(true);

            // 創(chuàng)建store,建立連接
            Store store = session.getStore(protocol);
            System.out.println("connecting");
            store.connect(mailHost, userName, password);
            System.out.println("connected successfully");
            setStore(store);
            return store;
           }

           /**
            * 打開(kāi)INBox文件夾
            */
           private Folder getFolderFromStore() {
            // 打開(kāi)郵件相應(yīng)文件夾
            Folder getFolder;
            try {
             getFolder = store.getFolder("INBOX");
             getFolder.open(Folder.READ_ONLY);
             setFolder(getFolder);
             return getFolder;
            } catch (MessagingException e) {
             // TODO Auto-generated catch block
             System.err.println("獲取Folder失敗!");
             e.printStackTrace();
            }
            return null;
           }

           /**
            * 從folder中提取所有的messages
            *
            * @throws MessagingException
            */
           public void getAllMessages() throws MessagingException {
            // 從郵件文件夾獲取郵件信息
            Message[] messages = folder.getMessages();
            setMessages(messages);
            setRecordFailure(); // 初始化出錯(cuò)數(shù)組
            // setMessageCount();
           }

           /**
            * 獲得messageNums數(shù)組指定的message
            *
            * @param messageNums
            * @throws MessagingException
            */
           public void getMessages(int[] messageNums) throws MessagingException {
            Message[] messages = folder.getMessages(messageNums);
            setMessages(messages);
            setRecordFailure(); // 初始化出錯(cuò)數(shù)組
            // setMessageCount();
           }

           /**
            * 獲得start和end之間的message
            *
            * @param start
            * @param end
            * @throws MessagingException
            */
           public void getMessages(int start, int end) throws MessagingException {
            Message[] messages = folder.getMessages(start, end);
            setMessages(messages);
            setRecordFailure(); // 初始化出錯(cuò)數(shù)組
            // setMessageCount();
           }

           /**
            * 關(guān)閉連接
            */
           public void closeConnection() {
            try {
             messages = null;
             message = null;
             if (folder.isOpen())
              folder.close(true);
             store.close();
             System.out.println("close");
            } catch (Exception e) {
             System.out.println("關(guān)閉和郵件服務(wù)器之間連接時(shí)出錯(cuò)!");
             e.printStackTrace();
            }
           }

           /**
            * 獲得當(dāng)前郵件的基本方法 Pop3Bean內(nèi)部應(yīng)該調(diào)用這個(gè)方法 以便在調(diào)用函數(shù)中加入重試機(jī)制
            *
            * @throws MessagingException
            * @throws MessagingException
            *
            */
           public void getMail() throws Throwable { // 拋出異常,用以重?cái)S
            try {
             saveMessageAs(message);
             parseMessage(message);
            } catch (IOException e) {
             // TODO Auto-generated catch block
             System.err.println("保存郵件出錯(cuò),檢查保存路徑");
             throw new IOException("保存郵件出錯(cuò),檢查保存路徑");
            } catch (MessagingException e) {
             // TODO Auto-generated catch block
             System.err.println("郵件轉(zhuǎn)換出錯(cuò)");
             throw new MessagingException("郵件轉(zhuǎn)換出錯(cuò)");
            } catch (Exception e) {
             System.err.println("未知錯(cuò)誤");
             otherError = true;
             e.printStackTrace();
             throw new Exception("未知錯(cuò)誤");
            }
           }

           /**
            * 獲得指定的郵件
            *
            * @param index
            */
           public void getMail(int index) {
            mailDownErrorCounter = 0; // 郵件下載出錯(cuò)計(jì)數(shù)器置零
            try { // 獲取郵件下載之前的錯(cuò)誤
             setMessage(messages[index]); // 設(shè)置當(dāng)前message
             System.out.println("正在獲取第" + index + "封郵件. . .");
             getMail(); // 獲取當(dāng)前message
             System.out.println("成功獲取第" + index + "封郵件");
            } catch (Throwable e) { // 獲得重?cái)S異常
             recordFailure[index] = true;
             mailDownErrorCounter++;
             System.err.println("下載第" + index + "封郵件時(shí)出錯(cuò)");
             retry();
            }
           }

           /**
            * 獲取messages中的所有郵件
            */
           public void getAllMail() {
            int mailArrayLength; // 將要下載的郵件的數(shù)量。若是重試時(shí),則為還未下載的郵件數(shù)量

            mailArrayLength = getMessageCount();

            System.out.println("一共有郵件" + mailArrayLength + "封");

            mailDownErrorCounter = 0; // 郵件下載出錯(cuò)計(jì)數(shù)器置零
            mailCounter = 0;
            for (int index = 0; index < mailArrayLength; index++) {
             try {
              setMessage(messages[index]); // 設(shè)置當(dāng)前message
              System.out.println("正在獲取第" + index + "封郵件. . .");
              getMail(); // 獲取當(dāng)前message
              System.out.println("成功獲取第" + index + "封郵件");
              mailCounter++;
             } catch (Throwable e) {
              otherError = false;
              recordFailure[index] = true;
              mailDownErrorCounter++;
              System.err.println("下載第" + index + "封郵件時(shí)出錯(cuò)");
             }
            }
            System.out.println("成功下載" + mailCounter + "封郵件");
            mailCounter = 0;
            if (mailDownErrorCounter != 0)
             retry();
           }

           /**
            * 保存郵件源文件
            */

           public void saveMessageAs(Message message) {
            String oriFileName;
            String fileExtend;

            try {
             oriFileName = getInfoBetweenBrackets(getMessageId(message)
               .toString());
             // 設(shè)置文件后綴名。若是附件則設(shè)法取得其文件后綴名作為將要保存文件的后綴名,若是正文部分則用.htm做后綴名
             String emlName = oriFileName;
             String fileNameWidthExtension = getEmlPath() + oriFileName
               + getExtension();
             File storeFile = new File(fileNameWidthExtension);
             for (int i = 0; storeFile.exists(); i++) {
              emlName = oriFileName + i;
              fileNameWidthExtension = getEmlPath() + emlName
                + getExtension();
              storeFile = new File(fileNameWidthExtension);
             }
             setEmlName(emlName);
             System.out.println("storefile's path: " + fileNameWidthExtension);
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             message.writeTo(baos);
             StringReader in = new StringReader(baos.toString());
             saveFile(fileNameWidthExtension, in);
            } catch (MessagingException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
            } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
            }
           }

           /*
            * 解析郵件
            */
           public void parseMessage(Message message) throws IOException,
             MessagingException {
            Object content = message.getContent();
            if (content instanceof Multipart) {
             handleMultipart((Multipart) content);
            } else {
             handlePart(message);
            }
           }

           /*
            * 解析Multipart
            */
           public void handleMultipart(Multipart multipart) throws MessagingException,
             IOException {
            for (int i = 0, n = multipart.getCount(); i < n; i++) {
             handlePart(multipart.getBodyPart(i));
            }
           }

           /*
            * 解析指定part,從中提取文件
            */
           public void handlePart(Part part) throws MessagingException, IOException {
            String disposition = part.getDisposition(); // Find attachment
            String contentType = part.getContentType();
            String str;
            InputStreamReader sbis = new InputStreamReader(part.getInputStream());
            if (disposition == null) { // When just body
             System.out.println("Null: " + contentType);
             // Check if plain
             if ((contentType.length() >= 9)
               && (contentType.toLowerCase().substring(0, 9)
                 .equals("text/plai"))) {

              System.out.println(getAttachPath() + getEmlName() + ".txt");
              saveFile(getAttachPath() + getEmlName() + ".txt", sbis);
             } else if ((contentType.length() >= 8) // Check if html
               && (contentType.toLowerCase().substring(0, 8)
                 .equals("text/htm"))) {
              saveFile(getAttachPath() + getEmlName() + ".html", sbis);
             } else if ((contentType.length() >= 9) // Check if html
               && (contentType.toLowerCase().substring(0, 9)
                 .equals("image/gif"))) {
              saveFile(getAttachPath() + getEmlName() + ".gif", sbis);
             } else if ((contentType.length() >= 10)
               && contentType.toLowerCase().substring(0, 10).equals(
                 "multipart/")) { // Check if multipart
              System.out.println("multipart body: " + contentType);
              Multipart mp = (Multipart) (part.getContent());
              handleMultipart(mp);
             } else { // Unknown type
              System.out.println("Other body: " + contentType);
              saveFile(getAttachPath() + getEmlName() + ".txt", sbis);
             }
            } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
             System.out.println("Attachment: " + part.getFileName() + " : "
               + contentType);
             // outToFile.println("Attachment: " + part.getFileName() + " : "
             // + contentType);
             saveFile(getAttachPath() + part.getFileName(), sbis);
            } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
             System.out.println("Inline: " + part.getFileName() + " : "
               + contentType);
             // outToFile.println("Inline: " + part.getFileName() + " : "
             // + contentType);
             saveFile(getAttachPath() + part.getFileName(), sbis);
            } else { // Should never happen
             System.out.println("Other: " + disposition);
             // outToFile.println("Other: " + disposition);
            }
           }

           public void saveFile(String fileName, Reader input) throws IOException {
            if (fileName == null) {
             fileName = File.createTempFile(getAttachPath() + "xx", ".out")
               .getName();
            }
            // Do no overwrite existing file
            File file = new File(fileName);
            int lastDot = fileName.lastIndexOf(".");
            String extension = fileName.substring(lastDot);
            String fullFileName = fileName;
            fileName = fileName.substring(0, lastDot);
            for (int i = 0; file.exists(); i++) {
             file = new File(fileName + i + extension);
            }
            FileWriter fos = new FileWriter(file);
            BufferedWriter bos = new BufferedWriter(fos);
            BufferedReader bis = new BufferedReader(input);
            int aByte;
            while ((aByte = bis.read()) != -1) {
             bos.write(aByte);
            }
            bos.flush();
            bos.close();
            bis.close();
           }

           public void readEmlFile(String fileName) throws MessagingException {
            try {
             // TODO readEmlFile
             InputStream fis = new FileInputStream(fileName);
             Object emlObj = (Object) fis;
             Session mailSession = Session.getDefaultInstance(System
               .getProperties(), null);
             MimeMessage msg = new MimeMessage(mailSession, fis);
             message = msg;

            } catch (FileNotFoundException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
            }
           }

           private String getInfoBetweenBrackets(String str) throws Exception {
            int i, j; // 用于標(biāo)識(shí)字符串中的"<"和">"的位置
            if (str == null) {
             str = "error";
             return str;
            }
            i = str.lastIndexOf("<");
            j = str.lastIndexOf(">");
            if (i != -1 && j != -1)
             str = str.substring(i + 1, j);
            return str;
           }

           // 當(dāng)有郵件無(wú)法下載時(shí)進(jìn)行重試
           private void retry() {
            mailCounter = 0;
            while (retryTimeCounter < totalRetryTimes && mailDownErrorCounter != 0) {
             if (!store.isConnected() || !folder.isOpen()) {
              System.err.println("與服務(wù)器連接斷開(kāi),請(qǐng)重新連接");
              closeConnection();
              return;
             }

             System.out.println("第" + (retryTimeCounter + 1) + "次重試");

             mailDownErrorCounter = 0; // 郵件下載出錯(cuò)計(jì)數(shù)器置零

             for (int index = 0; index < getMessageCount(); index++) {
              if (recordFailure[index]) {
               try {
                setMessage(messages[index]); // 設(shè)置當(dāng)前message
                System.out.println("正在獲取第" + index + "封郵件. . .");
                getMail(); // 獲取當(dāng)前message
                System.out.println("成功獲取第" + index + "封郵件");
                mailCounter++;
                recordFailure[index] = false;
               } catch (Throwable e) {
                otherError = false;
                recordFailure[index] = true;
                mailDownErrorCounter++;
                System.err.println("重新下載第" + index + "封郵件時(shí)出錯(cuò)");
               }
              }
             }
             retryTimeCounter++;
            }
            System.out.println("成功下載" + mailCounter + "封郵件");
            mailCounter = 0; // 將郵件計(jì)數(shù)置零
            mailDownErrorCounter = 0; // 下載錯(cuò)誤數(shù)量歸零
           }

           /*public static void main(String[] args) throws Throwable {

            try {
             Pop3Bean mail;
             mail = new Pop3Bean();
             mail.setUserName("superman_wshm");
             mail.setMailHost("pop3.126.com");
             mail.setPassword("wshmtt78");
             mail.setAttachPath("e:/");
             mail.setExtension(".eml");
             mail.setDateFormat("yyyydddd");

             mail.getConn();
             System.out.println("Count of messages in folder: "
               + mail.getAllMessageCount());
             System.out.println("Count of new messages in folder: "
               + mail.getNewMessageCount());
             System.out.println("Count of unread messages in folder: "
               + mail.getUnreadMessageCount());
             mail.getAllMessages();
             System.out.println("Count of loaded messages: "
               + mail.getMessageCount());
             mail.getAllMail();
             mail.setCurMessage(0);
             System.out.println(mail.getSubject());
             mail.closeConnection();
             // ReadEml mail = new
             // ReadEml("H:\\My_Soft_Works\\java\\jteam\\jmail\\received\\41C95D0F.008CD1.01099.eml");

            } catch (Exception e) {
             System.out.println("出現(xiàn)未預(yù)料的錯(cuò)誤!");
             e.printStackTrace();
            }
           }*/
          }

          主站蜘蛛池模板: 白玉县| 胶南市| 缙云县| 瑞昌市| 罗甸县| 仙桃市| 玉门市| 新巴尔虎左旗| 师宗县| 南城县| 山西省| 鄂伦春自治旗| 北票市| 长武县| 济源市| 泰兴市| 浪卡子县| 湖北省| 石家庄市| 永仁县| 芷江| 鹿邑县| 保山市| 宜兴市| 阆中市| 高雄县| 岳阳县| 施甸县| 惠水县| 乌鲁木齐市| 滨州市| 遂宁市| 黄冈市| 文昌市| 钦州市| 宜宾县| 泗阳县| 闽侯县| 顺平县| 隆尧县| 长宁县|