java Mail郵件接收工具類_java

來源:互聯網
上載者:User

下面是一個郵件接收的工具類,有點長!!!

public class ReciveMail {  private MimeMessage msg = null;   private String saveAttchPath = "";   private StringBuffer bodytext = new StringBuffer();   private String dateformate = "yy-MM-dd HH:mm";     public ReciveMail(MimeMessage msg){     this.msg = msg;     }   public void setMsg(MimeMessage msg) {     this.msg = msg;   }     /**    * 擷取發送郵件者資訊    * @return    * @throws MessagingException    */   public String getFrom() throws MessagingException{     InternetAddress[] address = (InternetAddress[]) msg.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;   }     /**    * 擷取郵件收件者,抄送,密送的地址和資訊。根據所傳遞的參數不同 "to"-->收件者,"cc"-->抄送人地址,"bcc"-->密送地址    * @param type    * @return    * @throws MessagingException    * @throws UnsupportedEncodingException    */   public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException{     String mailaddr = "";     String addrType = type.toUpperCase();     InternetAddress[] address = null;         if(addrType.equals("TO")||addrType.equals("CC")||addrType.equals("BCC")){       if(addrType.equals("TO")){         address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.TO);       }       if(addrType.equals("CC")){         address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.CC);       }       if(addrType.equals("BCC")){         address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.BCC);       }          if(address != null){         for(int i=0;i<address.length;i++){           String mail = address[i].getAddress();           if(mail == null){             mail = "";           }else{             mail = MimeUtility.decodeText(mail);           }           String personal = address[i].getPersonal();           if(personal == null){             personal = "";           }else{             personal = MimeUtility.decodeText(personal);           }           String compositeto = personal +"<"+mail+">";           mailaddr += ","+compositeto;         }         mailaddr = mailaddr.substring(1);       }     }else{       throw new RuntimeException("Error email Type!");     }     return mailaddr;   }     /**    * 擷取郵件主題    * @return    * @throws UnsupportedEncodingException    * @throws MessagingException    */   public String getSubject() throws UnsupportedEncodingException, MessagingException{     String subject = "";     subject = MimeUtility.decodeText(msg.getSubject());     if(subject == null){       subject = "";     }     return subject;   }     /**    * 擷取郵件發送日期    * @return    * @throws MessagingException    */   public String getSendDate() throws MessagingException{     Date sendDate = msg.getSentDate();     SimpleDateFormat smd = new SimpleDateFormat(dateformate);     return smd.format(sendDate);   }     /**    * 擷取郵件內文內容    * @return    */   public String getBodyText(){     return bodytext.toString();   }     /**    * 解析郵件,將得到的郵件內容儲存到一個stringBuffer對象中,    * 解析郵件 主要根據MimeType的不同執行不同的操作,一步一步的解析    * @param part    * @throws MessagingException    * @throws IOException    */   public void getMailContent(Part part) throws MessagingException, IOException{         String contentType = part.getContentType();     int nameindex = contentType.indexOf("name");     boolean conname = false;     if(nameindex != -1){       conname = true;     }     System.out.println("CONTENTTYPE:"+contentType);     if(part.isMimeType("text/plain")&&!conname){       bodytext.append((String)part.getContent());     }else if(part.isMimeType("text/html")&&!conname){       bodytext.append((String)part.getContent());     }else if(part.isMimeType("multipart/*")){       Multipart multipart = (Multipart) part.getContent();       int count = multipart.getCount();       for(int i=0;i<count;i++){         getMailContent(multipart.getBodyPart(i));       }     }else if(part.isMimeType("message/rfc822")){       getMailContent((Part) part.getContent());     }       }     /**    * 判斷郵件是否需要回執,如需回執返回true,否則返回false    * @return    * @throws MessagingException    */   public boolean getReplySign() throws MessagingException{     boolean replySign = false;     String needreply[] = msg.getHeader("Disposition-Notification-TO");     if(needreply != null){       replySign = true;     }     return replySign;   }     /**    * 擷取此郵件的message-id    * @return    * @throws MessagingException    */   public String getMessageId() throws MessagingException{     return msg.getMessageID();   }     /**    * 判斷此郵件是否已讀,如果未讀則返回false,已讀返回true    * @return    * @throws MessagingException    */   public boolean isNew() throws MessagingException{     boolean isnew = false;     Flags flags = ((Message)msg).getFlags();     Flags.Flag[] flag = flags.getSystemFlags();     System.out.println("flags's length:"+flag.length);     for(int i=0;i<flag.length;i++){       if(flag[i]==Flags.Flag.SEEN){         isnew = true;         System.out.println("seen message .......");         break;       }     }     return isnew;   }     /**    * 判斷是是否包含附件    * @param part    * @return    * @throws MessagingException    * @throws IOException    */   public boolean isContainAttch(Part part) throws MessagingException, IOException{     boolean flag = false;         //String contentType = part.getContentType();     if(part.isMimeType("multipart/*")){       Multipart multipart = (Multipart) part.getContent();       int count = multipart.getCount();       for(int i=0;i<count;i++){         BodyPart bodypart = multipart.getBodyPart(i);         String dispostion = bodypart.getDisposition();         if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){           flag = true;         }else if(bodypart.isMimeType("multipart/*")){           flag = isContainAttch(bodypart);         }else{           String conType = bodypart.getContentType();           if(conType.toLowerCase().indexOf("appliaction")!=-1){             flag = true;           }           if(conType.toLowerCase().indexOf("name")!=-1){             flag = true;           }         }       }     }else if(part.isMimeType("message/rfc822")){       flag = isContainAttch((Part) part.getContent());     }         return flag;   }     /**    * 儲存附件    * @param part    * @throws MessagingException    * @throws IOException    */   public void saveAttchMent(Part part) throws MessagingException, IOException{     String filename = "";     if(part.isMimeType("multipart/*")){       Multipart mp = (Multipart) part.getContent();       for(int i=0;i<mp.getCount();i++){         BodyPart mpart = mp.getBodyPart(i);         String dispostion = mpart.getDisposition();         if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){           filename = mpart.getFileName();           if(filename.toLowerCase().indexOf("gb2312")!=-1){             filename = MimeUtility.decodeText(filename);           }           saveFile(filename,mpart.getInputStream());         }else if(mpart.isMimeType("multipart/*")){           saveAttchMent(mpart);         }else{           filename = mpart.getFileName();           if(filename != null&&(filename.toLowerCase().indexOf("gb2312")!=-1)){             filename = MimeUtility.decodeText(filename);           }           saveFile(filename,mpart.getInputStream());         }       }           }else if(part.isMimeType("message/rfc822")){       saveAttchMent((Part) part.getContent());     }   }   /**    * 獲得儲存附件的地址    * @return    */   public String getSaveAttchPath() {     return saveAttchPath;   }   /**    * 設定儲存附件地址    * @param saveAttchPath    */   public void setSaveAttchPath(String saveAttchPath) {     this.saveAttchPath = saveAttchPath;   }   /**    * 設定日期格式    * @param dateformate    */   public void setDateformate(String dateformate) {     this.dateformate = dateformate;   }   /**    * 儲存檔案內容    * @param filename    * @param inputStream    * @throws IOException    */   private void saveFile(String filename, InputStream inputStream) throws IOException {     String osname = System.getProperty("os.name");     String storedir = getSaveAttchPath();     String sepatror = "";     if(osname == null){       osname = "";     }         if(osname.toLowerCase().indexOf("win")!=-1){       sepatror = "//";       if(storedir==null||"".equals(storedir)){         storedir = "d://temp";       }     }else{       sepatror = "/";       storedir = "/temp";     }         File storefile = new File(storedir+sepatror+filename);     System.out.println("storefile's path:"+storefile.toString());         BufferedOutputStream bos = null;     BufferedInputStream bis = null;         try {       bos = new BufferedOutputStream(new FileOutputStream(storefile));       bis = new BufferedInputStream(inputStream);       int c;       while((c= bis.read())!=-1){         bos.write(c);         bos.flush();       }     } catch (FileNotFoundException e) {       // TODO Auto-generated catch block       e.printStackTrace();     } catch (IOException e) {       // TODO Auto-generated catch block       e.printStackTrace();     }finally{       bos.close();       bis.close();     }       }     public void recive(Part part,int i) throws MessagingException, IOException{     System.out.println("------------------START-----------------------");     System.out.println("Message"+i+" subject:" + getSubject());     System.out.println("Message"+i+" from:" + getFrom());     System.out.println("Message"+i+" isNew:" + isNew());     boolean flag = isContainAttch(part);     System.out.println("Message"+i+" isContainAttch:" +flag);     System.out.println("Message"+i+" replySign:" + getReplySign());     getMailContent(part);     System.out.println("Message"+i+" content:" + getBodyText());     setSaveAttchPath("c://temp//"+i);     if(flag){       saveAttchMent(part);     }     System.out.println("------------------END-----------------------");   }}

郵件接收與工具類的使用,有好幾種郵件接收的寫法!:

看了很多網上其他代碼,pop3Server的值是pop.mail.163.com,但是試了試不成功,還有 user的值既可以是帶有 username@...com也可以是username。

如果收件郵箱是163郵箱,必須先登陸163郵箱中設定,開啟pop3服務。至於別的郵箱暫不知道。

public static void main(String[] args) throws Exception {     // 串連pop3伺服器的主機名稱、協議、使用者名稱、密碼     String pop3Server = "pop.163.com";     String protocol = "pop3";     String user = "username";     String pwd = "password";          // 建立一個有具體串連資訊的Properties對象     Properties props = new Properties();     props.setProperty("mail.store.protocol", protocol);     props.setProperty("mail.pop3.host", pop3Server);          // 使用Properties對象獲得Session對象     Session session = Session.getInstance(props);     session.setDebug(true);          // 利用Session對象獲得Store對象,並串連pop3伺服器     Store store = session.getStore();     store.connect(pop3Server, user, pwd);          // 獲得郵箱內的郵件夾Folder對象,以"唯讀"開啟     Folder folder = store.getFolder("inbox");     folder.open(Folder.READ_ONLY);          // 獲得郵件夾Folder內的所有郵件Message對象     Message [] messages = folder.getMessages();      ReciveMail rm = null;     for(int i=0;i< messages.size() ;i++){       rm = new ReciveMail((MimeMessage) messages[i]);       rm.recive(messages[i],i);;     }      folder.close(false);     store.close(); } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.