JavaMail学习笔记(四)使用POP3协议接收并解析电子邮件

来源:互联网 发布:it资产管理系统源码 编辑:程序博客网 时间:2024/06/11 19:18

 

[java] view plaincopyprint?
  1. package org.yangxin.study.jm; 
  2.  
  3. import java.io.BufferedInputStream; 
  4. import java.io.BufferedOutputStream;
  5. import java.io.File; 
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream; 
  8. import java.io.IOException; 
  9. import java.io.InputStream; 
  10. import java.io.UnsupportedEncodingException; 
  11. import java.text.SimpleDateFormat; 
  12. import java.util.Date; 
  13. import java.util.Properties; 
  14.  
  15. import javax.mail.Address; 
  16. import javax.mail.BodyPart; 
  17. import javax.mail.Flags; 
  18. import javax.mail.Folder; 
  19. import javax.mail.Message; 
  20. import javax.mail.MessagingException; 
  21. import javax.mail.Multipart; 
  22. import javax.mail.Part; 
  23. import javax.mail.Session; 
  24. import javax.mail.Store; 
  25. import javax.mail.internet.InternetAddress; 
  26. import javax.mail.internet.MimeMessage; 
  27. import javax.mail.internet.MimeMultipart; 
  28. import javax.mail.internet.MimeUtility; 
  29.  
  30. /**
  31. * 使用POP3协议接收邮件
  32. */ 
  33. public class POP3ReceiveMailTest { 
  34.      
  35.     public staticvoid main(String[] args) throws Exception { 
  36.         receive(); 
  37.     } 
  38.      
  39.     /**
  40.      * 接收邮件
  41.      */ 
  42.     public staticvoid receive() throws Exception { 
  43.         // 准备连接服务器的会话信息 
  44.         Properties props = new Properties(); 
  45.         props.setProperty("mail.store.protocol","pop3");       // 协议 
  46.         props.setProperty("mail.pop3.port","110");             // 端口 
  47.         props.setProperty("mail.pop3.host","pop3.163.com");    // pop3服务器 
  48.          
  49.         // 创建Session实例对象 
  50.         Session session = Session.getInstance(props); 
  51.         Store store = session.getStore("pop3"); 
  52.         store.connect("xyang0917@163.com","123456abc"); 
  53.          
  54.         // 获得收件箱 
  55.         Folder folder = store.getFolder("INBOX"); 
  56.         /* Folder.READ_ONLY:只读权限
  57.          * Folder.READ_WRITE:可读可写(可以修改邮件的状态)
  58.          */ 
  59.         folder.open(Folder.READ_WRITE); //打开收件箱 
  60.          
  61.         // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数 
  62.         System.out.println("未读邮件数: " + folder.getUnreadMessageCount()); 
  63.          
  64.         // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0 
  65.         System.out.println("删除邮件数: " + folder.getDeletedMessageCount()); 
  66.         System.out.println("新邮件: " + folder.getNewMessageCount()); 
  67.          
  68.         // 获得收件箱中的邮件总数 
  69.         System.out.println("邮件总数: " + folder.getMessageCount()); 
  70.          
  71.         // 得到收件箱中的所有邮件,并解析 
  72.         Message[] messages = folder.getMessages(); 
  73.         parseMessage(messages); 
  74.          
  75.         //释放资源 
  76.         folder.close(true); 
  77.         store.close(); 
  78.     } 
  79.      
  80.     /**
  81.      * 解析邮件
  82.      * @param messages 要解析的邮件列表
  83.      */ 
  84.     public staticvoid parseMessage(Message ...messages) throws MessagingException, IOException { 
  85.         if (messages == null || messages.length < 1)  
  86.             throw new MessagingException("未找到要解析的邮件!"); 
  87.          
  88.         // 解析所有邮件 
  89.         for (int i =0, count = messages.length; i < count; i++) { 
  90.             MimeMessage msg = (MimeMessage) messages[i]; 
  91.             System.out.println("------------------解析第" + msg.getMessageNumber() +"封邮件-------------------- "); 
  92.             System.out.println("主题: " + getSubject(msg)); 
  93.             System.out.println("发件人: " + getFrom(msg)); 
  94.             System.out.println("收件人:" + getReceiveAddress(msg,null)); 
  95.             System.out.println("发送时间:" + getSentDate(msg,null)); 
  96.             System.out.println("是否已读:" + isSeen(msg)); 
  97.             System.out.println("邮件优先级:" + getPriority(msg)); 
  98.             System.out.println("是否需要回执:" + isReplySign(msg)); 
  99.             System.out.println("邮件大小:" + msg.getSize() *1024 + "kb"); 
  100.             boolean isContainerAttachment = isContainAttachment(msg); 
  101.             System.out.println("是否包含附件:" + isContainerAttachment); 
  102.             if (isContainerAttachment) { 
  103.                 saveAttachment(msg, "c:\\mailtmp\\"+msg.getSubject() + "_");//保存附件 
  104.             }  
  105.             StringBuffer content = new StringBuffer(30); 
  106.             getMailTextContent(msg, content); 
  107.             System.out.println("邮件正文:" + (content.length() >100 ? content.substring(0,100) +"..." : content)); 
  108.             System.out.println("------------------第" + msg.getMessageNumber() +"封邮件解析结束-------------------- "); 
  109.             System.out.println(); 
  110.         } 
  111.     } 
  112.      
  113.     /**
  114.      * 获得邮件主题
  115.      * @param msg 邮件内容
  116.      * @return 解码后的邮件主题
  117.      */ 
  118.     public static String getSubject(MimeMessage msg)throws UnsupportedEncodingException, MessagingException { 
  119.         return MimeUtility.decodeText(msg.getSubject()); 
  120.     } 
  121.      
  122.     /**
  123.      * 获得邮件发件人
  124.      * @param msg 邮件内容
  125.      * @return 姓名 <Email地址>
  126.      * @throws MessagingException
  127.      * @throws UnsupportedEncodingException
  128.      */ 
  129.     public static String getFrom(MimeMessage msg)throws MessagingException, UnsupportedEncodingException { 
  130.         String from = ""
  131.         Address[] froms = msg.getFrom(); 
  132.         if (froms.length < 1
  133.             throw new MessagingException("没有发件人!"); 
  134.          
  135.         InternetAddress address = (InternetAddress) froms[0]; 
  136.         String person = address.getPersonal(); 
  137.         if (person != null) { 
  138.             person = MimeUtility.decodeText(person) + " "
  139.         } else
  140.             person = ""
  141.         } 
  142.         from = person + "<" + address.getAddress() +">"
  143.          
  144.         return from; 
  145.     } 
  146.      
  147.     /**
  148.      * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
  149.      * <p>Message.RecipientType.TO  收件人</p>
  150.      * <p>Message.RecipientType.CC  抄送</p>
  151.      * <p>Message.RecipientType.BCC 密送</p>
  152.      * @param msg 邮件内容
  153.      * @param type 收件人类型
  154.      * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
  155.      * @throws MessagingException
  156.      */ 
  157.     public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type)throws MessagingException { 
  158.         StringBuffer receiveAddress = new StringBuffer(); 
  159.         Address[] addresss = null
  160.         if (type == null) { 
  161.             addresss = msg.getAllRecipients(); 
  162.         } else
  163.             addresss = msg.getRecipients(type); 
  164.         } 
  165.          
  166.         if (addresss == null || addresss.length <1
  167.             throw new MessagingException("没有收件人!"); 
  168.         for (Address address : addresss) { 
  169.             InternetAddress internetAddress = (InternetAddress)address; 
  170.             receiveAddress.append(internetAddress.toUnicodeString()).append(","); 
  171.         } 
  172.          
  173.         receiveAddress.deleteCharAt(receiveAddress.length()-1);//删除最后一个逗号 
  174.          
  175.         return receiveAddress.toString(); 
  176.     } 
  177.      
  178.     /**
  179.      * 获得邮件发送时间
  180.      * @param msg 邮件内容
  181.      * @return yyyy年mm月dd日 星期X HH:mm
  182.      * @throws MessagingException
  183.      */ 
  184.     public static String getSentDate(MimeMessage msg, String pattern)throws MessagingException { 
  185.         Date receivedDate = msg.getSentDate(); 
  186.         if (receivedDate == null
  187.             return ""
  188.          
  189.         if (pattern == null || "".equals(pattern)) 
  190.             pattern = "yyyy年MM月dd日 E HH:mm "
  191.          
  192.         return new SimpleDateFormat(pattern).format(receivedDate); 
  193.     } 
  194.      
  195.     /**
  196.      * 判断邮件中是否包含附件
  197.      * @param msg 邮件内容
  198.      * @return 邮件中存在附件返回true,不存在返回false
  199.      * @throws MessagingException
  200.      * @throws IOException
  201.      */ 
  202.     public staticboolean isContainAttachment(Part part) throws MessagingException, IOException { 
  203.         boolean flag = false
  204.         if (part.isMimeType("multipart/*")) { 
  205.             MimeMultipart multipart = (MimeMultipart) part.getContent(); 
  206.             int partCount = multipart.getCount(); 
  207.             for (int i =0; i < partCount; i++) { 
  208.                 BodyPart bodyPart = multipart.getBodyPart(i); 
  209.                 String disp = bodyPart.getDisposition(); 
  210.                 if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
  211.                     flag = true
  212.                 } else if (bodyPart.isMimeType("multipart/*")) { 
  213.                     flag = isContainAttachment(bodyPart); 
  214.                 } else
  215.                     String contentType = bodyPart.getContentType(); 
  216.                     if (contentType.indexOf("application") != -1) { 
  217.                         flag = true
  218.                     }   
  219.                      
  220.                     if (contentType.indexOf("name") != -1) { 
  221.                         flag = true
  222.                     }  
  223.                 } 
  224.                  
  225.                 if (flag)break
  226.             } 
  227.         } else if (part.isMimeType("message/rfc822")) { 
  228.             flag = isContainAttachment((Part)part.getContent()); 
  229.         } 
  230.         return flag; 
  231.     } 
  232.      
  233.     /** 
  234.      * 判断邮件是否已读 
  235.      * @param msg 邮件内容 
  236.      * @return 如果邮件已读返回true,否则返回false 
  237.      * @throws MessagingException  
  238.      */ 
  239.     public staticboolean isSeen(MimeMessage msg) throws MessagingException { 
  240.         return msg.getFlags().contains(Flags.Flag.SEEN); 
  241.     } 
  242.      
  243.     /**
  244.      * 判断邮件是否需要阅读回执
  245.      * @param msg 邮件内容
  246.      * @return 需要回执返回true,否则返回false
  247.      * @throws MessagingException
  248.      */ 
  249.     public staticboolean isReplySign(MimeMessage msg) throws MessagingException { 
  250.         boolean replySign = false
  251.         String[] headers = msg.getHeader("Disposition-Notification-To"); 
  252.         if (headers != null
  253.             replySign = true
  254.         return replySign; 
  255.     } 
  256.      
  257.     /**
  258.      * 获得邮件的优先级
  259.      * @param msg 邮件内容
  260.      * @return 1(High):紧急  3:普通(Normal)  5:低(Low)
  261.      * @throws MessagingException
  262.      */ 
  263.     public static String getPriority(MimeMessage msg)throws MessagingException { 
  264.         String priority = "普通"
  265.         String[] headers = msg.getHeader("X-Priority"); 
  266.         if (headers != null) { 
  267.             String headerPriority = headers[0]; 
  268.             if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1
  269.                 priority = "紧急"
  270.             else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1
  271.                 priority = "低"
  272.             else 
  273.                 priority = "普通"
  274.         } 
  275.         return priority; 
  276.     }  
  277.      
  278.     /**
  279.      * 获得邮件文本内容
  280.      * @param part 邮件体
  281.      * @param content 存储邮件文本内容的字符串
  282.      * @throws MessagingException
  283.      * @throws IOException
  284.      */ 
  285.     public staticvoid getMailTextContent(Part part, StringBuffer content)throws MessagingException, IOException { 
  286.         //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断 
  287.         boolean isContainTextAttach = part.getContentType().indexOf("name") >0;  
  288.         if (part.isMimeType("text/*") && !isContainTextAttach) { 
  289.             content.append(part.getContent().toString()); 
  290.         } else if (part.isMimeType("message/rfc822")) {  
  291.             getMailTextContent((Part)part.getContent(),content); 
  292.         } else if (part.isMimeType("multipart/*")) { 
  293.             Multipart multipart = (Multipart) part.getContent(); 
  294.             int partCount = multipart.getCount(); 
  295.             for (int i =0; i < partCount; i++) { 
  296.                 BodyPart bodyPart = multipart.getBodyPart(i); 
  297.                 getMailTextContent(bodyPart,content); 
  298.             } 
  299.         } 
  300.     } 
  301.      
  302.     /** 
  303.      * 保存附件 
  304.      * @param part 邮件中多个组合体中的其中一个组合体 
  305.      * @param destDir  附件保存目录 
  306.      * @throws UnsupportedEncodingException 
  307.      * @throws MessagingException 
  308.      * @throws FileNotFoundException 
  309.      * @throws IOException 
  310.      */ 
  311.     public staticvoid saveAttachment(Part part, String destDir)throws UnsupportedEncodingException, MessagingException, 
  312.             FileNotFoundException, IOException { 
  313.         if (part.isMimeType("multipart/*")) { 
  314.             Multipart multipart = (Multipart) part.getContent();    //复杂体邮件 
  315.             //复杂体邮件包含多个邮件体 
  316.             int partCount = multipart.getCount(); 
  317.             for (int i =0; i < partCount; i++) { 
  318.                 //获得复杂体邮件中其中一个邮件体 
  319.                 BodyPart bodyPart = multipart.getBodyPart(i); 
  320.                 //某一个邮件体也有可能是由多个邮件体组成的复杂体 
  321.                 String disp = bodyPart.getDisposition(); 
  322.                 if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) { 
  323.                     InputStream is = bodyPart.getInputStream(); 
  324.                     saveFile(is, destDir, decodeText(bodyPart.getFileName())); 
  325.                 } else if (bodyPart.isMimeType("multipart/*")) { 
  326.                     saveAttachment(bodyPart,destDir); 
  327.                 } else
  328.                     String contentType = bodyPart.getContentType(); 
  329.                     if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) { 
  330.                         saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName())); 
  331.                     } 
  332.                 } 
  333.             } 
  334.         } else if (part.isMimeType("message/rfc822")) { 
  335.             saveAttachment((Part) part.getContent(),destDir); 
  336.         } 
  337.     } 
  338.      
  339.     /** 
  340.      * 读取输入流中的数据保存至指定目录 
  341.      * @param is 输入流 
  342.      * @param fileName 文件名 
  343.      * @param destDir 文件存储目录 
  344.      * @throws FileNotFoundException 
  345.      * @throws IOException 
  346.      */ 
  347.     private staticvoid saveFile(InputStream is, String destDir, String fileName) 
  348.             throws FileNotFoundException, IOException { 
  349.         BufferedInputStream bis = new BufferedInputStream(is); 
  350.         BufferedOutputStream bos = new BufferedOutputStream( 
  351.                 new FileOutputStream(new File(destDir + fileName))); 
  352.         int len = -1
  353.         while ((len = bis.read()) != -1) { 
  354.             bos.write(len); 
  355.             bos.flush(); 
  356.         } 
  357.         bos.close(); 
  358.         bis.close(); 
  359.     } 
  360.      
  361.     /**
  362.      * 文本解码
  363.      * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
  364.      * @return 解码后的文本
  365.      * @throws UnsupportedEncodingException
  366.      */ 
  367.     public static String decodeText(String encodeText)throws UnsupportedEncodingException { 
  368.         if (encodeText == null ||"".equals(encodeText)) { 
  369.             return ""
  370.         } else
  371.             return MimeUtility.decodeText(encodeText); 
  372.         } 
  373.     } 

测试结果: