afunms

          My Software,My Dream—Forge a more perfect NMS product.

          java email

          package afu.mymail;

          import java.io.*;
          import javax.mail.internet.*;
          import javax.mail.*;
          import java.util.*;

          public class RecieveMail
          {
              
          public RecieveMail()
              
          {
              }


              
          public void getMails(final String targetFolder) throws Exception
              
          {
                  Properties props 
          = new Properties();
                  Session session 
          = Session.getDefaultInstance(props, null);
                  Store store 
          = session.getStore("pop3");
                  store.connect(
          "pop.126.com","username","password");
                  Folder folder 
          = store.getFolder("INBOX");    
                  
          if(folder==null)
                  
          {
                       System.out.println(
          "Sorry,can not find the inbox folder");
                       
          return;
                  }

                  folder.open(Folder.READ_WRITE);
                  Message[] messages 
          = folder.getMessages();    
                  
          if(messages.length==0//郵箱里沒有郵件
                  {
                      System.out.println(
          "Sorry,there are no email for you");
                      folder.close(
          true);
                      
          return;
                  }

                  
                  System.out.println(
          "Congratulate,you have " + messages.length + " new emails");
                  
          for(int i=0;i < messages.length;i++)
                  
          {               
                      String mailSubject 
          = getSubject(messages[i]);
                      String emailfile 
          = targetFolder + mailSubject + ".html";
                      System.out.println(emailfile);

                      PrintWriter outFile 
          = null;
                      
          try
                      
          {
                          outFile 
          = new PrintWriter(new FileOutputStream(new File(emailfile)));
                          outFile.println(
          "郵件來源:" + getSourceEmailAddress(messages[i]) + "<br>");
                          outFile.println(parseMailContent(messages[i]));
                          messages[i].setFlag(Flags.Flag.DELETED,
          true); //delete email on server
                      }

                      
          catch(Exception e)
                      
          {
                          System.out.println(
          "wrote mail " + mailSubject + " failed.");
                          
          //e.printStackTrace();                 
                      }

                      
          finally
                      
          {
                          outFile.close();    
                      }

                  }

                  folder.close(
          true);
                  store.close();
              }


              
          /**
               * get email's subject
               
          */

              
          private String getSubject(final Message msg) throws MessagingException
              
          {
                  String[] subjects 
          = msg.getHeader("Subject");
                  
          if(subjects==nullreturn getCurrentLongTime();
                  
                  
          /**
                   * may be more one subjects,but they have the same content
                   
          */

                  
          if(subjects[0]==null||subjects[0].equals("")) 
                      
          return getCurrentLongTime();
                  
                  String subject 
          = decodeText(subjects[0]);
                  
          int loc = subject.indexOf(" ");        
                  
          if(loc==-1)
                     
          return subject;
                  
          else
                  
          {
                      loc 
          = subject.indexOf(" ",loc + 1);
                      
          return subject.substring(loc + 1);
                  }

              }

              
              
          /**
               * get current time
               
          */

              
          private String getCurrentLongTime()
              
          {
                    
          return String.valueOf((new java.util.Date()).getTime());       
              }
              
              
              
          /**
               * email body is very complex,
               * this method parse email body to a string
               
          */

              
          private String parseMailContent(final Message msg) throws Exception
              
          {             
                  
          if(msg.getContent() instanceof String)
                        
          return (String)msg.getContent();
              
                  StringBuffer mailContent 
          = new StringBuffer(1000);
                  Multipart multiPart 
          = (Multipart)msg.getContent();      
                  String multiPartType 
          = multiPart.getContentType();
                
                  BodyPart bodyPart 
          = multiPart.getBodyPart(0);
                  
          if(bodyPart.getContent() instanceof String)
                     mailContent.append((String)bodyPart.getContent());
                  
          else if(bodyPart.getContent() instanceof MimeMultipart)
                     mailContent.append(((MimeMultipart)bodyPart.getContent()).getBodyPart(
          0).getContent());
                        
                    
          /**
                     * deal with attachment
                     
          */

                  
          if(multiPartType.startsWith("multipart/mixed"))
                  
          {
                      mailContent.append(
          "<br>-----------附件:-----------<br>"); 
                      
          for(int c = 1;c < multiPart.getCount(); c++)   
                      
          {              
                          String fn 
          = extractAttachmentFileName(multiPart.getBodyPart(c).getContentType());
                          mailContent.append(fn).append(
          "<br>"); 
                      }
           
                  }

                  
          return mailContent.toString();
              }

            
              
          /**
               * get source email address
               
          */

              
          private String getSourceEmailAddress(final Message msg) throws MessagingException
              
          {
                  String address 
          = InternetAddress.toString(msg.getFrom());
                  
          int foreindex = address.indexOf("<");
                  
          int backindex = address.indexOf(">");
                  
          if(foreindex == -1 || backindex == -1)
                      
          return address;
                  
          return address.substring(foreindex + 1,backindex);
              }

            
             
          /**
              * contentType contains attachment file name 
              * this method extract the file name from contentType string.
              
          */

              
          private String extractAttachmentFileName(final String contentType)
              
          {
                  
          int loc = contentType.indexOf("name=");
                  String fileName 
          = contentType.substring(loc + 6,contentType.length()-1);
                        
                  
          return decodeText(fileName);
              }


              
          private String decodeText(final String contentText)
              
          {
                  String dt 
          = null;
                  
          try
                  
          {
                      dt 
          = MimeUtility.decodeText(contentText);
                  }

                  
          catch (UnsupportedEncodingException E)
                  
          {
                      dt 
          = "";   
                  }

                  
          return dt;
              }

                 
              
          public static void main(String[] args)
              
          {
                  
          try
                  
          {
                      RecieveMail rm 
          = new RecieveMail();
                      rm.getMails(
          "D:\\resume\\0826\\");
                  }

                  
          catch(Exception e)
                  
          {
                      e.printStackTrace();
                  }

              }

          }

          自動收取email,每個email生成一個html文件。不處理附件。

          posted on 2008-08-28 15:43 afunms 閱讀(255) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          My Links

          News

          留言簿(18)

          隨筆檔案

          相冊

          搜索

          最新評論

          閱讀排行榜

          主站蜘蛛池模板: 深水埗区| 密山市| 治多县| 中方县| 孝感市| 萨迦县| 沛县| 登封市| 偃师市| 临泽县| 大同县| 鸡东县| 内黄县| 石门县| 南部县| 黑龙江省| 屏南县| 奉新县| 普兰店市| 岫岩| 庆阳市| 资兴市| 当雄县| 佛山市| 嵩明县| 石狮市| 阿拉善左旗| 汽车| 孝感市| 布尔津县| 镇安县| 永新县| 清镇市| 漠河县| 博爱县| 环江| 缙云县| 东莞市| 什邡市| 长海县| 临江市|