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.  * 有一封郵件就需要建立一個ReciveMail對象

  8.  */

  9. public class ReciveOneMail {   

  10.     private MimeMessage mimeMessage = null;   

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

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

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

  14.     public ReciveOneMail(MimeMessage mimeMessage) {   

  15.         this.mimeMessage = mimeMessage;   

  16.     }   

  17.     public void setMimeMessage(MimeMessage mimeMessage) {   

  18.         this.mimeMessage = mimeMessage;   

  19.     }   

  20.     /**

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

  22.      */

  23.     public String getFrom() throws Exception {   

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

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

  26.         if (from == null)   

  27.             from = "";   

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

  29.         if (personal == null)   

  30.             personal = "";   

  31.         String fromaddr = personal + "<"< span=""> + from + ">";   

  32.         return fromaddr;   

  33.     }   

  34.     /**

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

  36.      */

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

  38.         String mailaddr = "";   

  39.         String addtype = type.toUpperCase();   

  40.         InternetAddress[] address = null;   

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

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

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

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

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

  46.             } else {   

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

  48.             }   

  49.             if (address != null) {   

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

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

  52.                     if (email == null)   

  53.                         email = "";   

  54.                     else {   

  55.                         email = MimeUtility.decodeText(email);   

  56.                     }   

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

  58.                     if (personal == null)   

  59.                         personal = "";   

  60.                     else {   

  61.                         personal = MimeUtility.decodeText(personal);   

  62.                     }   

  63.                     String compositeto = personal + "<"< span=""> + email + ">";   

  64.                     mailaddr += "," + compositeto;   

  65.                 }   

  66.                 mailaddr = mailaddr.substring(1);   

  67.             }   

  68.         } else {   

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

  70.         }   

  71.         return mailaddr;   

  72.     }   

  73.     /**

  74.      * 獲得郵件主題

  75.      */

  76.     public String getSubject() throws MessagingException {   

  77.         String subject = "";   

  78.         try {   

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

  80.             if (subject == null)   

  81.                 subject = "";   

  82.         } catch (Exception exce) {}   

  83.         return subject;   

  84.     }   

  85.     /**

  86.      * 獲得郵件發送日期

  87.      */

  88.     public String getSentDate() throws Exception {   

  89.         Date sentdate = mimeMessage.getSentDate();   

  90.         SimpleDateFormat format = new SimpleDateFormat(dateformat);   

  91.         return format.format(sentdate);   

  92.     }   

  93.     /**

  94.      * 獲得郵件正文內容

  95.      */

  96.     public String getBodyText() {   

  97.         return bodytext.toString();   

  98.     }   

  99.     /**

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

  101.      */

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

  103.         String contenttype = part.getContentType();   

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

  105.         boolean conname = false;   

  106.         if (nameindex != -1)   

  107.             conname = true;   

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

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

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

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

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

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

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

  115.             int counts = multipart.getCount();   

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

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

  118.             }   

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

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

  121.         } else {}   

  122.     }   

  123.     /**   

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

  125.      */   

  126.     public boolean getReplySign() throws MessagingException {   

  127.         boolean replysign = false;   

  128.         String needreply[] = mimeMessage   

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

  130.         if (needreply != null) {   

  131.             replysign = true;   

  132.         }   

  133.         return replysign;   

  134.     }   

  135.     /**

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

  137.      */

  138.     public String getMessageId() throws MessagingException {   

  139.         return mimeMessage.getMessageID();   

  140.     }   

  141.     /**

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

  143.      */

  144.     public boolean isNew() throws MessagingException {   

  145.         boolean isnew = false;   

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

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

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

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

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

  151.                 isnew = true;   

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

  153.                 break;   

  154.             }   

  155.         }   

  156.         return isnew;   

  157.     }   

  158.     /**

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

  160.      */

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

  162.         boolean attachflag = false;   

  163.         String contentType = part.getContentType();   

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

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

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

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

  168.                 String disposition = mpart.getDisposition();   

  169.                 if ((disposition != null)   

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

  171.                                 .equals(Part.INLINE))))   

  172.                     attachflag = true;   

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

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

  175.                 } else {   

  176.                     String contype = mpart.getContentType();   

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

  178.                         attachflag = true;   

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

  180.                         attachflag = true;   

  181.                 }   

  182.             }   

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

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

  185.         }   

  186.         return attachflag;   

  187.     }   

  188.     /**   

  189.      * 【保存附件】   

  190.      */   

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

  192.         String fileName = "";   

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

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

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

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

  197.                 String disposition = mpart.getDisposition();   

  198.                 if ((disposition != null)   

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

  200.                                 .equals(Part.INLINE)))) {   

  201.                     fileName = mpart.getFileName();   

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

  203.                         fileName = MimeUtility.decodeText(fileName);   

  204.                     }   

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

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

  207.                     saveAttachMent(mpart);   

  208.                 } else {   

  209.                     fileName = mpart.getFileName();   

  210.                     if ((fileName != null)   

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

  212.                         fileName = MimeUtility.decodeText(fileName);   

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

  214.                     }   

  215.                 }   

  216.             }   

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

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

  219.         }   

  220.     }   

  221.     /**   

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

  223.      */   

  224.     public void setAttachPath(String attachpath) {   

  225.         this.saveAttachPath = attachpath;   

  226.     }   

  227.     /**

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

  229.      */

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

  231.         this.dateformat = format;   

  232.     }   

  233.     /**

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

  235.      */

  236.     public String getAttachPath() {   

  237.         return saveAttachPath;   

  238.     }   

  239.     /**

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

  241.      */

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

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

  244.         String storedir = getAttachPath();   

  245.         String separator = "";   

  246.         if (osName == null)   

  247.             osName = "";   

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

  249.             separator = "\\\\";

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

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

  252.         } else {

  253.             separator = "/";

  254.             storedir = "/tmp";

  255.         }

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

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

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

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

  260.         // }

  261.         BufferedOutputStream bos = null;

  262.         BufferedInputStream bis = null;

  263.         try {

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

  265.             bis = new BufferedInputStream(in);

  266.             int c;

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

  268.                 bos.write(c);

  269.                 bos.flush();

  270.             }

  271.         } catch (Exception exception) {

  272.             exception.printStackTrace();

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

  274.         } finally {

  275.             bos.close();

  276.             bis.close();

  277.         }

  278.     }

  279.  

  280.     /**

  281.      * PraseMimeMessage類測試

  282.      */

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

  284.         Properties props = System.getProperties();

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

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

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

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

  289.                 "xiangzhengyan", "pass");

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

  291.         store.connect();

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

  293.         folder.open(Folder.READ_ONLY);

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

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

  296.         ReciveOneMail pmm = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  315.                     + pmm.getBodyText());

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

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

  318.         }   

  319.     }   

  320. }  

   

分享到:       sina.jpg\"       tec.jpg\"    

第一個Hibernate with Annotation程式(轉 ...      |       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的博客\"

xiangzhengyan

  • 瀏覽: 63611 次

  • 性別: \"Icon_minigender_1\"

  • 來自: 北京

  • offline.gif\"

最近訪客 更多訪客>>

\"dylinshi126的博客\"

dylinshi126

\"shuitao.cao的博客\"

shuitao.cao

\"smile_clj的博客\"

smile_clj

\"Hundun_Wu的博客\"

Hundun_Wu

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

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

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

 

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