android pop3与imap方式接收邮件(javamail)

需要下载3个jar包:mail.jar/    activation.jar/    additionnal.jar

1.pop3

[html]  view plain copy
  1. /**  
  2.  * 以pop3方式读取邮件,此方法不能读取邮件是否为已读,已经通过测试  
  3.  * */  
  4. private void getEmail() {  
  5.     List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  6.   
  7.     try {  
  8.         Properties props = System.getProperties();  
  9.         props.put("mail.smtp.host", "smtp.163.com");  
  10.         props.put("mail.smtp.auth", "true");  
  11.         Session session = Session.getDefaultInstance(props, null);  
  12.         URLName urln = new URLName("pop3", "pop3.163.com", 110, null,  
  13.                 "邮箱名(没有@163.com)", "密码");  
  14.         // 邮件协议为pop3,邮件服务器是pop3.163.com,端口为110,用户名/密码为abcw111222/123456w  
  15.         Store store = session.getStore(urln);  
  16.         store.connect();  
  17.         Folder folder = store.getFolder("INBOX");  
  18.         folder.open(Folder.READ_WRITE);  
  19.         Message message[] = folder.getMessages();  
  20.         if (message.length > 0) {  
  21.             Map<String, Object> map;  
  22.             System.out.println("Messages's length: " + message.length);  
  23.             ReciveOneMail pmm = null;  
  24.             for (int i = 0; i < message.length; i++) {  
  25.                 System.out.println("======================");  
  26.                 pmm = new ReciveOneMail((MimeMessage) message[i]);  
  27.                 System.out.println("Message " + i + " subject: "  
  28.                         + pmm.getSubject());  
  29.                 System.out.println("Message " + i + " sentdate: "  
  30.                         + pmm.getSentDate());  
  31.                 System.out.println("Message " + i + " replysign: "  
  32.                         + pmm.getReplySign());  
  33.   
  34.                 boolean isRead = pmm.isNew();// 判断邮件是否为已读  
  35.                 System.out.println("Message " + i + " hasRead: " + isRead);  
  36.                 System.out.println("Message " + i + "  containAttachment: "  
  37.                         + pmm.isContainAttach((Part) message[i]));  
  38.                 System.out.println("Message " + i + " form: "  
  39.                         + pmm.getFrom());  
  40.                 System.out.println("Message " + i + " to: "  
  41.                         + pmm.getMailAddress("to"));  
  42.                 System.out.println("Message " + i + " cc: "  
  43.                         + pmm.getMailAddress("cc"));  
  44.                 System.out.println("Message " + i + " bcc: "  
  45.                         + pmm.getMailAddress("bcc"));  
  46.                 pmm.setDateFormat("yy年MM月dd日 HH:mm");  
  47.                 System.out.println("Message " + i + " sentdate: "  
  48.                         + pmm.getSentDate());  
  49.                 System.out.println("Message " + i + " Message-ID: "  
  50.                         + pmm.getMessageId());  
  51.                 // 获得邮件内容===============  
  52.                 pmm.getMailContent((Part) message[i]);  
  53.                 System.out.println("Message " + i + " bodycontent: \r\n"  
  54.                         + pmm.getBodyText());  
  55.                 String file_path = File.separator + "mnt" + File.separator  
  56.                         + "sdcard" + File.separator;  
  57.                 System.out.println(file_path);  
  58.                 pmm.setAttachPath(file_path);  
  59.                 pmm.saveAttachMent((Part) message[i]);  
  60.   
  61.                 map = new HashMap<String, Object>();  
  62.                 map.put("from", pmm.getFrom());  
  63.                 map.put("title", pmm.getSubject());  
  64.                 map.put("time", pmm.getSentDate());  
  65.                 map.put("read", isRead);  
  66.                 list.add(map);  
  67.             }  
  68.             SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,  
  69.                     list, R.layout.item_receiveemail, new String[] {  
  70.                             "from", "title", "time", "read" }, new int[] {  
  71.                             R.id.item_receive_sendname,  
  72.                             R.id.item_receive_title,  
  73.                             R.id.item_receive_sendtime,  
  74.                             R.id.item_receive_read });  
  75.             lv.setAdapter(adapter);  
  76.   
  77.         } else {  
  78.             Toast.makeText(MainActivity.this, "没有邮件", Toast.LENGTH_SHORT)  
  79.                     .show();  
  80.         }  
  81.     } catch (NoSuchProviderException e) {  
  82.         // TODO Auto-generated catch block  
  83.         e.printStackTrace();  
  84.     } catch (MessagingException e) {  
  85.         // TODO Auto-generated catch block  
  86.         e.printStackTrace();  
  87.     } catch (Exception e) {  
  88.         // TODO Auto-generated catch block  
  89.         e.printStackTrace();  
  90.     }  
  91. }  
2.imap方式

[html]  view plain copy
  1. /**  
  2.  * 以imap方式读取邮件,可以判定读取邮件是否为已读  
  3.  * */  
  4. private void getImapEmail() {  
  5.     String user = "[email protected]";// 邮箱的用户名  
  6.     String password = "123456w"; // 邮箱的密码  
  7.   
  8.     Properties prop = System.getProperties();  
  9.     prop.put("mail.store.protocol", "imap");  
  10.     prop.put("mail.imap.host", "imap.163.com");  
  11.   
  12.     Session session = Session.getInstance(prop);  
  13.   
  14.     int total = 0;  
  15.     IMAPStore store;  
  16.     try {  
  17.         store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器  
  18.   
  19.         store.connect(user, password);  
  20.   
  21.         IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱  
  22.         folder.open(Folder.READ_WRITE);  
  23.         // 获取总邮件数  
  24.         total = folder.getMessageCount();  
  25.         System.out.println("---共有邮件:" + total + " 封---");  
  26.         // 得到收件箱文件夹信息,获取邮件列表  
  27.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  28.         System.out.println("未读邮件数:" + folder.getUnreadMessageCount());  
  29.         Message[] messages = folder.getMessages();  
  30.         if (messages.length > 0) {  
  31.             Map<String, Object> map;  
  32.             System.out.println("Messages's length: " + messages.length);  
  33.             ReciveOneMail pmm = null;  
  34.             for (int i = 0; i < messages.length; i++) {  
  35.                 System.out.println("======================");  
  36.                 pmm = new ReciveOneMail((MimeMessage) messages[i]);  
  37.                 System.out.println("Message " + i + " subject: "  
  38.                         + pmm.getSubject());  
  39.                 try {  
  40.                     System.out.println("Message " + i + " sentdate: "  
  41.                             + pmm.getSentDate());  
  42.                     System.out.println("Message " + i + " replysign: "  
  43.                             + pmm.getReplySign());  
  44.   
  45.                     boolean isRead;// 用来判断该邮件是否为已读  
  46.                     String read;  
  47.                     Flags flags = messages[i].getFlags();  
  48.                     if (flags.contains(Flags.Flag.SEEN)) {  
  49.                         System.out.println("这是一封已读邮件");  
  50.                         isRead = true;  
  51.                         read = "已读";  
  52.                     } else {  
  53.                         System.out.println("未读邮件");  
  54.                         isRead = false;  
  55.                         read = "未读";  
  56.                     }  
  57.                     System.out.println("Message " + i + " hasRead: "  
  58.                             + isRead);  
  59.                     System.out.println("Message " + i  
  60.                             + "  containAttachment: "  
  61.                             + pmm.isContainAttach((Part) messages[i]));  
  62.                     System.out.println("Message " + i + " form: "  
  63.                             + pmm.getFrom());  
  64.                     System.out.println("Message " + i + " to: "  
  65.                             + pmm.getMailAddress("to"));  
  66.                     System.out.println("Message " + i + " cc: "  
  67.                             + pmm.getMailAddress("cc"));  
  68.                     System.out.println("Message " + i + " bcc: "  
  69.                             + pmm.getMailAddress("bcc"));  
  70.                     pmm.setDateFormat("yy年MM月dd日 HH:mm");  
  71.                     System.out.println("Message " + i + " sentdate: "  
  72.                             + pmm.getSentDate());  
  73.                     System.out.println("Message " + i + " Message-ID: "  
  74.                             + pmm.getMessageId());  
  75.                     // 获得邮件内容===============  
  76.                     pmm.getMailContent((Part) messages[i]);  
  77.                     System.out.println("Message " + i  
  78.                             + " bodycontent: \r\n" + pmm.getBodyText());  
  79.                     String file_path = File.separator + "mnt"  
  80.                             + File.separator + "sdcard" + File.separator;  
  81.                     System.out.println(file_path);  
  82.                     pmm.setAttachPath(file_path);  
  83.                     pmm.saveAttachMent((Part) messages[i]);  
  84.   
  85.                     map = new HashMap<String, Object>();  
  86.                     map.put("from", pmm.getFrom());  
  87.                     map.put("title", pmm.getSubject());  
  88.                     map.put("time", pmm.getSentDate());  
  89.                     map.put("read", read);  
  90.                     list.add(map);  
  91.                 } catch (Exception e) {  
  92.                     // TODO Auto-generated catch block  
  93.                     e.printStackTrace();  
  94.                 }  
  95.   
  96.             }  
  97.             SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,  
  98.                     list, R.layout.item_receiveemail, new String[] {  
  99.                             "from", "title", "time", "read" }, new int[] {  
  100.                             R.id.item_receive_sendname,  
  101.                             R.id.item_receive_title,  
  102.                             R.id.item_receive_sendtime,  
  103.                             R.id.item_receive_read });  
  104.             lv.setAdapter(adapter);  
  105.         }  
  106.     } catch (javax.mail.NoSuchProviderException e) {  
  107.         // TODO Auto-generated catch block  
  108.         e.printStackTrace();  
  109.     } catch (MessagingException e) {  
  110.         // TODO Auto-generated catch block  
  111.         e.printStackTrace();  
  112.     }  
  113.   
  114. }  
下面为用到的一个类,用来读取除了判断是否已读的信息之外的内容

[html]  view plain copy
  1. /**  
  2.  * 接收邮箱中的邮件,可以接收带附件的  
  3.  * (目前接收的邮件中含有中文内容,会出现乱码,但是标题不会乱码)  
  4.  * 邮件中的内容如果用专门的阅读器也不会出现乱码现象,图片等都可以下载  
  5.  * */  
  6. @SuppressLint("DefaultLocale")  
  7. public class ReciveOneMail {  
  8.   
  9.     private MimeMessage mimeMessage = null;  
  10.     private String saveAttachPath = ""; // 附件下载后的存放目录  
  11.     private StringBuffer bodytext = new StringBuffer();// 存放邮件内容  
  12.     private String dateformat = "yy-MM-dd HH:mm"; // 默认的日前显示格式  
  13.   
  14.     public ReciveOneMail(MimeMessage mimeMessage) {  
  15.         this.mimeMessage = mimeMessage;  
  16.     }  
  17.   
  18.     public void setMimeMessage(MimeMessage mimeMessage) {  
  19.         this.mimeMessage = mimeMessage;  
  20.     }  
  21.   
  22.     /**  
  23.      * 获得发件人的地址和姓名  
  24.      */  
  25.     public String getFrom() throws Exception {  
  26.         InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();  
  27.         String from = address[0].getAddress();  
  28.         if (from == null)  
  29.             from = "";  
  30.         String personal = address[0].getPersonal();  
  31.         if (personal == null)  
  32.             personal = "";  
  33.         String fromaddr = personal + "<" + from + ">";  
  34.         return fromaddr;  
  35.     }  
  36.   
  37.     /**  
  38.      * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址  
  39.      */  
  40.     @SuppressLint("DefaultLocale")  
  41.     public String getMailAddress(String type) throws Exception {  
  42.         String mailaddr = "";  
  43.         String addtype = type.toUpperCase();  
  44.         InternetAddress[] address = null;  
  45.         if (addtype.equals("TO") || addtype.equals("CC")  
  46.                 || addtype.equals("BCC")) {  
  47.             if (addtype.equals("TO")) {  
  48.                 address = (InternetAddress[]) mimeMessage  
  49.                         .getRecipients(Message.RecipientType.TO);  
  50.             } else if (addtype.equals("CC")) {  
  51.                 address = (InternetAddress[]) mimeMessage  
  52.                         .getRecipients(Message.RecipientType.CC);  
  53.             } else {  
  54.                 address = (InternetAddress[]) mimeMessage  
  55.                         .getRecipients(Message.RecipientType.BCC);  
  56.             }  
  57.             if (address != null) {  
  58.                 for (int i = 0; i < address.length; i++) {  
  59.                     String email = address[i].getAddress();  
  60.                     if (email == null)  
  61.                         email = "";  
  62.                     else {  
  63.                         email = MimeUtility.decodeText(email);  
  64.                     }  
  65.                     String personal = address[i].getPersonal();  
  66.                     if (personal == null)  
  67.                         personal = "";  
  68.                     else {  
  69.                         personal = MimeUtility.decodeText(personal);  
  70.                     }  
  71.                     String compositeto = personal + "<" + email + ">";  
  72.                     mailaddr += "," + compositeto;  
  73.                 }  
  74.                 mailaddr = mailaddr.substring(1);  
  75.             }  
  76.         } else {  
  77.             throw new Exception("Error emailaddr type!");  
  78.         }  
  79.         return mailaddr;  
  80.     }  
  81.   
  82.     /**  
  83.      * 获得邮件主题  
  84.      */  
  85.     public String getSubject() throws MessagingException {  
  86.         String subject = "";  
  87.         try {  
  88.             subject = MimeUtility.decodeText(mimeMessage.getSubject());  
  89.             if (subject == null)  
  90.                 subject = "";  
  91.         } catch (Exception exce) {  
  92.         }  
  93.         return subject;  
  94.     }  
  95.   
  96.     /**  
  97.      * 获得邮件发送日期  
  98.      */  
  99.     @SuppressLint("SimpleDateFormat")  
  100.     public String getSentDate() throws Exception {  
  101.         Date sentdate = mimeMessage.getSentDate();  
  102.         SimpleDateFormat format = new SimpleDateFormat(dateformat);  
  103.         return format.format(sentdate);  
  104.     }  
  105.   
  106.     /**  
  107.      * 获得邮件正文内容  
  108.      */  
  109.     public String getBodyText() {  
  110.         return bodytext.toString();  
  111.     }  
  112.   
  113.     /**  
  114.      * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析  
  115.      */  
  116.     public void getMailContent(Part part) throws Exception {  
  117.         String contenttype = part.getContentType();  
  118.         int nameindex = contenttype.indexOf("name");  
  119.         boolean conname = false;  
  120.         if (nameindex != -1)  
  121.             conname = true;  
  122.         System.out.println("CONTENTTYPE: " + contenttype);  
  123.         if (part.isMimeType("text/plain") && !conname) {  
  124.             bodytext.append((String) part.getContent());  
  125.         } else if (part.isMimeType("text/html") && !conname) {  
  126.             bodytext.append((String) part.getContent());  
  127.         } else if (part.isMimeType("multipart/*")) {  
  128.             Multipart multipart = (Multipart) part.getContent();  
  129.             int counts = multipart.getCount();  
  130.             for (int i = 0; i < counts; i++) {  
  131.                 getMailContent(multipart.getBodyPart(i));  
  132.             }  
  133.         } else if (part.isMimeType("message/rfc822")) {  
  134.             getMailContent((Part) part.getContent());  
  135.         } else {  
  136.         }  
  137.     }  
  138.   
  139.     /**  
  140.      * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"  
  141.      */  
  142.     public boolean getReplySign() throws MessagingException {  
  143.         boolean replysign = false;  
  144.         String needreply[] = mimeMessage  
  145.                 .getHeader("Disposition-Notification-To");  
  146.         if (needreply != null) {  
  147.             replysign = true;  
  148.         }  
  149.         return replysign;  
  150.     }  
  151.   
  152.     /**  
  153.      * 获得此邮件的Message-ID  
  154.      */  
  155.     public String getMessageId() throws MessagingException {  
  156.         return mimeMessage.getMessageID();  
  157.     }  
  158.   
  159.     /**  
  160.      * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】pop3协议使用时不能判断。  
  161.      */  
  162.     public boolean isNew() throws MessagingException {  
  163.         boolean isnew = false;//由于isnew设为false所以每次显示的都为未读  
  164.         Flags flags = ((Message) mimeMessage).getFlags();  
  165.         System.out.println("--------flags-------" + flags);  
  166.         Flags.Flag[] flag = flags.getSystemFlags();  
  167.         System.out.println("----flag----" + flag);  
  168.         System.out.println("flags's length: " + flag.length);  
  169.         for (int i = 0; i < flag.length; i++) {  
  170.             System.out.println("flag=======" + flag[i]);  
  171.             System.out.println("-=-=-=Flags.Flag.SEEN=-=-=-="+Flags.Flag.SEEN);  
  172.             if (flag[i] == Flags.Flag.SEEN) {  
  173.                 isnew = true;  
  174.                 System.out.println("seen Message.......");  
  175.                 break;  
  176.             }  
  177.         }  
  178.         return isnew;  
  179.     }  
  180.   
  181.     /**  
  182.      * 判断此邮件是否包含附件  
  183.      */  
  184.     @SuppressLint("DefaultLocale")  
  185.     public boolean isContainAttach(Part part) throws Exception {  
  186.         boolean attachflag = false;  
  187.         // String contentType = part.getContentType();  
  188.         if (part.isMimeType("multipart/*")) {  
  189.             Multipart mp = (Multipart) part.getContent();  
  190.             for (int i = 0; i < mp.getCount(); i++) {  
  191.                 BodyPart mpart = mp.getBodyPart(i);  
  192.                 String disposition = mpart.getDisposition();  
  193.                 if ((disposition != null)  
  194.                         && ((disposition.equals(Part.ATTACHMENT)) || (disposition  
  195.                                 .equals(Part.INLINE))))  
  196.                     attachflag = true;  
  197.                 else if (mpart.isMimeType("multipart/*")) {  
  198.                     attachflag = isContainAttach((Part) mpart);  
  199.                 } else {  
  200.                     String contype = mpart.getContentType();  
  201.                     if (contype.toLowerCase().indexOf("application") != -1)  
  202.                         attachflag = true;  
  203.                     if (contype.toLowerCase().indexOf("name") != -1)  
  204.                         attachflag = true;  
  205.                 }  
  206.             }  
  207.         } else if (part.isMimeType("message/rfc822")) {  
  208.             attachflag = isContainAttach((Part) part.getContent());  
  209.         }  
  210.         return attachflag;  
  211.     }  
  212.   
  213.     /**  
  214.      * 【保存附件】  
  215.      */  
  216.     @SuppressLint("DefaultLocale")  
  217.     public void saveAttachMent(Part part) throws Exception {  
  218.         String fileName = "";  
  219.         if (part.isMimeType("multipart/*")) {  
  220.             Multipart mp = (Multipart) part.getContent();  
  221.             for (int i = 0; i < mp.getCount(); i++) {  
  222.                 BodyPart mpart = mp.getBodyPart(i);//主体部分得到处理  
  223.                 String disposition = mpart.getDisposition();  
  224.                 if ((disposition != null)  
  225.                         && ((disposition.equals(Part.ATTACHMENT)) || (disposition  
  226.                                 .equals(Part.INLINE)))) {//ATTACHMENT附件,INLINE嵌入  
  227.                     fileName = mpart.getFileName();  
  228.                     if (fileName.toLowerCase().indexOf("gb18030") != -1) {  
  229.                         fileName = MimeUtility.decodeText(fileName);  
  230.                     }  
  231.                     saveFile(fileName, mpart.getInputStream());  
  232.                 } else if (mpart.isMimeType("multipart/*")) {  
  233.                     saveAttachMent(mpart);  
  234.                 } else {  
  235.                     fileName = mpart.getFileName();  
  236.                     if ((fileName != null)  
  237.                             && (fileName.toLowerCase().indexOf("GB18030") != -1)) {  
  238.                         fileName = MimeUtility.decodeText(fileName);  
  239.                         saveFile(fileName, mpart.getInputStream());  
  240.                     }  
  241.                 }  
  242.             }  
  243.         } else if (part.isMimeType("message/rfc822")) {  
  244.             saveAttachMent((Part) part.getContent());  
  245.         }  
  246.     }  
  247.   
  248.     /**  
  249.      * 【设置附件存放路径】  
  250.      */  
  251.   
  252.     public void setAttachPath(String attachpath) {  
  253.         this.saveAttachPath = attachpath;  
  254.     }  
  255.   
  256.     /**  
  257.      * 【设置日期显示格式】  
  258.      */  
  259.     public void setDateFormat(String format) throws Exception {  
  260.         this.dateformat = format;  
  261.     }  
  262.   
  263.     /**  
  264.      * 【获得附件存放路径】  
  265.      */  
  266.     public String getAttachPath() {  
  267.         return saveAttachPath;  
  268.     }  
  269.   
  270.     /**  
  271.      * 【真正的保存附件到指定目录里】  
  272.      */  
  273.     @SuppressLint("DefaultLocale")  
  274.     private void saveFile(String fileName, InputStream in) throws Exception {  
  275.         String osName = System.getProperty("os.name");  
  276.         System.out.println("----fileName----" + fileName);  
  277.         // String storedir = getAttachPath();  
  278. //      String separator = "";  
  279.         if (osName == null)  
  280.             osName = "";  
  281.         File storefile = new File(File.separator + "mnt" + File.separator  
  282.                 + "sdcard" + File.separator + fileName);  
  283.   
  284.         storefile.createNewFile();  
  285.         System.out.println("storefile's path: " + storefile.toString());  
  286. //       for(int i=0;storefile.exists();i++){  
  287. //       storefile = new File(storedir+separator+fileName+i);  
  288. //       }  
  289.   
  290.         BufferedOutputStream bos = null;  
  291.         BufferedInputStream bis = null;  
  292.         try {  
  293.             bos = new BufferedOutputStream(new FileOutputStream(storefile));  
  294.             bis = new BufferedInputStream(in);  
  295.             int c;  
  296.             while ((c = bis.read()) != -1) {  
  297.                 bos.write(c);  
  298.                 bos.flush();  
  299.             }  
  300.         } catch (Exception exception) {  
  301.             exception.printStackTrace();  
  302.             throw new Exception("文件保存失败!");  
  303.         } finally {  
  304.             bos.close();  
  305.             bis.close();  
  306.         }  
  307.     }  
  308. }  

你可能感兴趣的:(android,pop3,javamail,imap)