Receive 163 mails

首頁   資訊   精華   論壇   問答   博客   專欄   羣組   更多  

招聘搜索

您還未登錄 !     登錄     註冊  

XZY的學習筆記

xiangzhengyan

javamail接收郵件(較全)          

博客分類:Java EE

CC++C#OS 

java 代碼

  1. import java.io.*;   

  2. import java.text.*;   

  3. import java.util.*;   

  4. import javax.mail.*;   

  5. import javax.mail.internet.*;   

  6.   

  7. /**  

  8.  * 有一封郵件就需要建立一個ReciveMail對象  

  9.  */  

  10. public class ReciveOneMail {   

  11.     private MimeMessage mimeMessage = null;   

  12.     private String saveAttachPath = ""//附件下載後的存放目錄   

  13.     private StringBuffer bodytext = new StringBuffer();//存放郵件內容   

  14.     private String dateformat = "yy-MM-dd HH:mm"//默認的日前顯示格式   

  15.   

  16.     public ReciveOneMail(MimeMessage mimeMessage) {   

  17.         this.mimeMessage = mimeMessage;   

  18.     }   

  19.   

  20.     public void setMimeMessage(MimeMessage mimeMessage) {   

  21.         this.mimeMessage = mimeMessage;   

  22.     }   

  23.   

  24.     /**  

  25.      * 獲得發件人的地址和姓名  

  26.      */  

  27.     public String getFrom() throws Exception {   

  28.         InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();   

  29.         String from = address[0].getAddress();   

  30.         if (from == null)   

  31.             from = "";   

  32.         String personal = address[0].getPersonal();   

  33.         if (personal == null)   

  34.             personal = "";   

  35.         String fromaddr = personal + "<" + from + ">";   

  36.         return fromaddr;   

  37.     }   

  38.   

  39.     /**  

  40.      * 獲得郵件的收件人,抄送,和密送的地址和姓名,根據所傳遞的參數的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址  

  41.      */  

  42.     public String getMailAddress(String type) throws Exception {   

  43.         String mailaddr = "";   

  44.         String addtype = type.toUpperCase();   

  45.         InternetAddress[] address = null;   

  46.         if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {   

  47.             if (addtype.equals("TO")) {   

  48.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);   

  49.             } else if (addtype.equals("CC")) {   

  50.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);   

  51.             } else {   

  52.                 address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);   

  53.             }   

  54.             if (address != null) {   

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

  56.                     String email = address[i].getAddress();   

  57.                     if (email == null)   

  58.                         email = "";   

  59.                     else {   

  60.                         email = MimeUtility.decodeText(email);   

  61.                     }   

  62.                     String personal = address[i].getPersonal();   

  63.                     if (personal == null)   

  64.                         personal = "";   

  65.                     else {   

  66.                         personal = MimeUtility.decodeText(personal);   

  67.                     }   

  68.                     String compositeto = personal + "<" + email + ">";   

  69.                     mailaddr += "," + compositeto;   

  70.                 }   

  71.                 mailaddr = mailaddr.substring(1);   

  72.             }   

  73.         } else {   

  74.             throw new Exception("Error emailaddr type!");   

  75.         }   

  76.         return mailaddr;   

  77.     }   

  78.   

  79.     /**  

  80.      * 獲得郵件主題  

  81.      */  

  82.     public String getSubject() throws MessagingException {   

  83.         String subject = "";   

  84.         try {   

  85.             subject = MimeUtility.decodeText(mimeMessage.getSubject());   

  86.             if (subject == null)   

  87.                 subject = "";   

  88.         } catch (Exception exce) {}   

  89.         return subject;   

  90.     }   

  91.   

  92.     /**  

  93.      * 獲得郵件發送日期  

  94.      */  

  95.     public String getSentDate() throws Exception {   

  96.         Date sentdate = mimeMessage.getSentDate();   

  97.         SimpleDateFormat format = new SimpleDateFormat(dateformat);   

  98.         return format.format(sentdate);   

  99.     }   

  100.   

  101.     /**  

  102.      * 獲得郵件正文內容  

  103.      */  

  104.     public String getBodyText() {   

  105.         return bodytext.toString();   

  106.     }   

  107.   

  108.     /**  

  109.      * 解析郵件,把得到的郵件內容保存到一個StringBuffer對象中,解析郵件 主要是根據MimeType類型的不同執行不同的操作,一步一步的解析  

  110.      */  

  111.     public void getMailContent(Part part) throws Exception {   

  112.         String contenttype = part.getContentType();   

  113.         int nameindex = contenttype.indexOf("name");   

  114.         boolean conname = false;   

  115.         if (nameindex != -1)   

  116.             conname = true;   

  117.         System.out.println("CONTENTTYPE: " + contenttype);   

  118.         if (part.isMimeType("text/plain") && !conname) {   

  119.             bodytext.append((String) part.getContent());   

  120.         } else if (part.isMimeType("text/html") && !conname) {   

  121.             bodytext.append((String) part.getContent());   

  122.         } else if (part.isMimeType("multipart/*")) {   

  123.             Multipart multipart = (Multipart) part.getContent();   

  124.             int counts = multipart.getCount();   

  125.             for (int i = 0; i < counts; i++) {   

  126.                 getMailContent(multipart.getBodyPart(i));   

  127.             }   

  128.         } else if (part.isMimeType("message/rfc822")) {   

  129.             getMailContent((Part) part.getContent());   

  130.         } else {}   

  131.     }   

  132.   

  133.     /**   

  134.      * 判斷此郵件是否需要回執,如果需要回執返回"true",否則返回"false"  

  135.      */   

  136.     public boolean getReplySign() throws MessagingException {   

  137.         boolean replysign = false;   

  138.         String needreply[] = mimeMessage   

  139.                 .getHeader("Disposition-Notification-To");   

  140.         if (needreply != null) {   

  141.             replysign = true;   

  142.         }   

  143.         return replysign;   

  144.     }   

  145.   

  146.     /**  

  147.      * 獲得此郵件的Message-ID  

  148.      */  

  149.     public String getMessageId() throws MessagingException {   

  150.         return mimeMessage.getMessageID();   

  151.     }   

  152.   

  153.     /**  

  154.      * 【判斷此郵件是否已讀,如果未讀返回返回false,反之返回true】  

  155.      */  

  156.     public boolean isNew() throws MessagingException {   

  157.         boolean isnew = false;   

  158.         Flags flags = ((Message) mimeMessage).getFlags();   

  159.         Flags.Flag[] flag = flags.getSystemFlags();   

  160.         System.out.println("flags's length: " + flag.length);   

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

  162.             if (flag[i] == Flags.Flag.SEEN) {   

  163.                 isnew = true;   

  164.                 System.out.println("seen Message.......");   

  165.                 break;   

  166.             }   

  167.         }   

  168.         return isnew;   

  169.     }   

  170.   

  171.     /**  

  172.      * 判斷此郵件是否包含附件  

  173.      */  

  174.     public boolean isContainAttach(Part part) throws Exception {   

  175.         boolean attachflag = false;   

  176.         String contentType = part.getContentType();   

  177.         if (part.isMimeType("multipart/*")) {   

  178.             Multipart mp = (Multipart) part.getContent();   

  179.             for (int i = 0; i < mp.getCount(); i++) {   

  180.                 BodyPart mpart = mp.getBodyPart(i);   

  181.                 String disposition = mpart.getDisposition();   

  182.                 if ((disposition != null)   

  183.                         && ((disposition.equals(Part.ATTACHMENT)) || (disposition   

  184.                                 .equals(Part.INLINE))))   

  185.                     attachflag = true;   

  186.                 else if (mpart.isMimeType("multipart/*")) {   

  187.                     attachflag = isContainAttach((Part) mpart);   

  188.                 } else {   

  189.                     String contype = mpart.getContentType();   

  190.                     if (contype.toLowerCase().indexOf("application") != -1)   

  191.                         attachflag = true;   

  192.                     if (contype.toLowerCase().indexOf("name") != -1)   

  193.                         attachflag = true;   

  194.                 }   

  195.             }   

  196.         } else if (part.isMimeType("message/rfc822")) {   

  197.             attachflag = isContainAttach((Part) part.getContent());   

  198.         }   

  199.         return attachflag;   

  200.     }   

  201.   

  202.     /**   

  203.      * 【保存附件】   

  204.      */   

  205.     public void saveAttachMent(Part part) throws Exception {   

  206.         String fileName = "";   

  207.         if (part.isMimeType("multipart/*")) {   

  208.             Multipart mp = (Multipart) part.getContent();   

  209.             for (int i = 0; i < mp.getCount(); i++) {   

  210.                 BodyPart mpart = mp.getBodyPart(i);   

  211.                 String disposition = mpart.getDisposition();   

  212.                 if ((disposition != null)   

  213.                         && ((disposition.equals(Part.ATTACHMENT)) || (disposition   

  214.                                 .equals(Part.INLINE)))) {   

  215.                     fileName = mpart.getFileName();   

  216.                     if (fileName.toLowerCase().indexOf("gb2312") != -1) {   

  217.                         fileName = MimeUtility.decodeText(fileName);   

  218.                     }   

  219.                     saveFile(fileName, mpart.getInputStream());   

  220.                 } else if (mpart.isMimeType("multipart/*")) {   

  221.                     saveAttachMent(mpart);   

  222.                 } else {   

  223.                     fileName = mpart.getFileName();   

  224.                     if ((fileName != null)   

  225.                             && (fileName.toLowerCase().indexOf("GB2312") != -1)) {   

  226.                         fileName = MimeUtility.decodeText(fileName);   

  227.                         saveFile(fileName, mpart.getInputStream());   

  228.                     }   

  229.                 }   

  230.             }   

  231.         } else if (part.isMimeType("message/rfc822")) {   

  232.             saveAttachMent((Part) part.getContent());   

  233.         }   

  234.     }   

  235.   

  236.     /**   

  237.      * 【設置附件存放路徑】   

  238.      */   

  239.   

  240.     public void setAttachPath(String attachpath) {   

  241.         this.saveAttachPath = attachpath;   

  242.     }   

  243.   

  244.     /**  

  245.      * 【設置日期顯示格式】  

  246.      */  

  247.     public void setDateFormat(String format) throws Exception {   

  248.         this.dateformat = format;   

  249.     }   

  250.   

  251.     /**  

  252.      * 【獲得附件存放路徑】  

  253.      */  

  254.     public String getAttachPath() {   

  255.         return saveAttachPath;   

  256.     }   

  257.   

  258.     /**  

  259.      * 【真正的保存附件到指定目錄裏】  

  260.      */  

  261.     private void saveFile(String fileName, InputStream in) throws Exception {   

  262.         String osName = System.getProperty("os.name");   

  263.         String storedir = getAttachPath();   

  264.         String separator = "";   

  265.         if (osName == null)   

  266.             osName = "";   

  267.         if (osName.toLowerCase().indexOf("win") != -1) {   

  268.             separator = "\\";  

  269.             if (storedir == null || storedir.equals(""))  

  270.                 storedir = "c:\\tmp";  

  271.         } else {  

  272.             separator = "/";  

  273.             storedir = "/tmp";  

  274.         }  

  275.         File storefile = new File(storedir + separator + fileName);  

  276.         System.out.println("storefile's path: " + storefile.toString());  

  277.         // for(int i=0;storefile.exists();i++){  

  278.         // storefile = new File(storedir+separator+fileName+i);  

  279.         // }  

  280.         BufferedOutputStream bos = null;  

  281.         BufferedInputStream bis = null;  

  282.         try {  

  283.             bos = new BufferedOutputStream(new FileOutputStream(storefile));  

  284.             bis = new BufferedInputStream(in);  

  285.             int c;  

  286.             while ((c = bis.read()) != -1) {  

  287.                 bos.write(c);  

  288.                 bos.flush();  

  289.             }  

  290.         } catch (Exception exception) {  

  291.             exception.printStackTrace();  

  292.             throw new Exception("文件保存失敗!");  

  293.         } finally {  

  294.             bos.close();  

  295.             bis.close();  

  296.         }  

  297.     }  

  298.  

  299.     /**  

  300.      * PraseMimeMessage類測試  

  301.      */  

  302.     public static void main(String args[]) throws Exception {  

  303.         Properties props = System.getProperties();  

  304.         props.put("mail.smtp.host", "smtp.163.com");  

  305.         props.put("mail.smtp.auth", "true");  

  306.         Session session = Session.getDefaultInstance(props, null);  

  307.         URLName urln = new URLName("pop3", "pop3.163.com", 110, null,  

  308.                 "xiangzhengyan", "pass");  

  309.         Store store = session.getStore(urln);  

  310.         store.connect();  

  311.         Folder folder = store.getFolder("INBOX");  

  312.         folder.open(Folder.READ_ONLY);  

  313.         Message message[] = folder.getMessages();  

  314.         System.out.println("Messages's length: " + message.length);  

  315.         ReciveOneMail pmm = null;  

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

  317.             System.out.println("======================");  

  318.             pmm = new ReciveOneMail((MimeMessage) message[i]);  

  319.             System.out.println("Message " + i + " subject: " + pmm.getSubject());  

  320.             System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());  

  321.             System.out.println("Message " + i + " replysign: "+ pmm.getReplySign());  

  322.             System.out.println("Message " + i + " hasRead: " + pmm.isNew());  

  323.             System.out.println("Message " + i + "  containAttachment: "+ pmm.isContainAttach((Part) message[i]));  

  324.             System.out.println("Message " + i + " form: " + pmm.getFrom());  

  325.             System.out.println("Message " + i + " to: "+ pmm.getMailAddress("to"));  

  326.             System.out.println("Message " + i + " cc: "+ pmm.getMailAddress("cc"));  

  327.             System.out.println("Message " + i + " bcc: "+ pmm.getMailAddress("bcc"));  

  328.             pmm.setDateFormat("yy年MM月dd日 HH:mm");  

  329.             System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());  

  330.             System.out.println("Message " + i + " Message-ID: "+ pmm.getMessageId());  

  331.             // 獲得郵件內容===============  

  332.             pmm.getMailContent((Part) message[i]);  

  333.             System.out.println("Message " + i + " bodycontent: \r\n"  

  334.                     + pmm.getBodyText());  

  335.             pmm.setAttachPath("c:\\");   

  336.             pmm.saveAttachMent((Part) message[i]);   

  337.         }   

  338.     }   

  339. }  

   

分享到:       sina.jpg       tec.jpg    

     |       javamail發送郵件(簡)    

評論

   

14 樓     hsjshijiazhuang    2014-03-03  

另外再指出,此程序針對於windows vista 以上系統,c盤是拒絕訪問的,所以還得在其它盤符下創建附件文件,或者獲得訪問權限icon_biggrin.gif

13 樓     hsjshijiazhuang    2014-03-03  

這裏面有錯誤,我修改了,具體修改是:第216行中,if語句中增加((fileName != null)),第219行的saveFile方法挪到if語句裏面。就不會報錯了

12 樓     llxiyuel    2014-03-01  

大哥,怎麼解析郵件正文輸出純文本

11 樓     yiwanxinyuefml    2014-01-26  

請教一個問題,不知道其他人有沒碰到過:就是用javamail接收的郵件,正文、附件都可以正常接收,但是郵件正文有一些換行符之類的東西,接收到之後寫入到一個文件卻是一整串沒有換行符的字符串???

10 樓     amwyyyy    2013-11-29  

不錯不錯icon_biggrin.gif icon_biggrin.gif icon_biggrin.gif icon_biggrin.gif

9 樓     spy41s    2013-07-23  

中文會亂碼。。。

8 樓     tigerwood008    2012-01-07  

如果有附件的哈,好像會有內存溢出的問題,這個該怎麼解決!

7 樓     fuanyu    2011-10-14  

確實比較全  但是我試了  郵件內容部分還是有問題耶 能否再詳細解說下哦

6 樓     嘻哈方式     2011-05-26  

確實比較全  但是我試了  郵件內容部分還是有問題耶 能否再詳細解說下哦

5 樓     zyh_1986    2010-09-21  

寫得真不錯!從裏面學到不少網上很難找的東西,多謝……

4 樓     bsspirit    2010-08-12  

這個不錯,很有幫助!!

3 樓     DepthJava    2010-04-12  

封裝的很不錯,亂碼問題怎麼解決的?

2 樓     containsoft    2009-11-23  

大哥,問你個問題,郵件收取進來,並保存爲文件之後,要在web頁面裏一條一條的顯示出郵件的日期,標題,發件人,點擊進去,查看郵件具體內容,這該怎麼做呢。能指點指點麼。我郵箱[email protected]

1 樓     maweiqiang    2008-06-04  

你好啊,你的這個接受郵件我看了,確實寫的很不錯啊,我們老師也讓我們做一個收發郵件,但是收郵件這裏我不太明白,麻煩你能把你收郵件的代碼包括頁面給我看下嗎。非常感謝啊,大哥我的郵箱是[email protected]

發表評論

login_icon.png  您還沒有登錄,請您登錄後再發表評論

xiangzhengyan

  • 瀏覽: 63611 次

  • 性別: Icon_minigender_1

  • 來自: 北京

  • offline.gif

最近訪客 更多訪客>>

dylinshi126

shuitao.cao

smile_clj

Hundun_Wu

文章分類
社區版塊
存檔分類
最新評論

聲明:ITeye文章版權屬於作者,受法律保護。沒有作者書面許可不得轉載。若作者同意轉載,必須以超鏈接形式標明文章原始出處和作者。
2003-2014 ITeye.com.   All rights reserved.  [ 京ICP證110151號  京公網安備110105010620 ]

?url=http%3A%2F%2Fxiangzhengyan.iteye.co          

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章