打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
黑马 JavaMail加深总结pop3协议收邮件
  1. package com.skycn.pop3;  
  2.   
  3. import java.io.File;  
  4. import java.util.Properties;  
  5. /*** 
  6.  * 收邮件基本信息 
  7.  * @author tianzhw 
  8.  * 
  9.  */  
  10. public class MailReceiverInfo {  
  11.     //邮件服务器IP和端口和协议   
  12.     private String mailServerHost;  
  13.     private String mailServerPost;  
  14.     private String protpcal = "pop3";  
  15.     //登录邮件服务器的用户名和密码   
  16.     private String userName;  
  17.     private String passWord;  
  18.     //保存邮件的路径   
  19.     private String attchmentDir = "";  
  20.     private String emailDir = "";  
  21.     private String emailFileSuffix = ".eml";  
  22.     //是否要确认身份   
  23.     private boolean vaildate = true;  
  24.     //获得邮件的属性初始化   
  25.     public Properties getProperties() {  
  26.         Properties properties = new Properties();  
  27.         properties.put("mail.pop3.host", mailServerHost);  
  28.         properties.put("mail.pop3.port", mailServerPost);  
  29.         properties.put("mail.pop3.auth", vaildate ? "true" : "false");  
  30.         return properties;  
  31.     }  
  32.   
  33.     public String getMailServerHost() {  
  34.         return mailServerHost;  
  35.     }  
  36.   
  37.     public void setMailServerHost(String mailServerHost) {  
  38.         this.mailServerHost = mailServerHost;  
  39.     }  
  40.   
  41.     public String getMailServerPost() {  
  42.         return mailServerPost;  
  43.     }  
  44.   
  45.     public void setMailServerPost(String mailServerPost) {  
  46.         this.mailServerPost = mailServerPost;  
  47.     }  
  48.   
  49.     public String getProtpcal() {  
  50.         return protpcal;  
  51.     }  
  52.   
  53.     public void setProtpcal(String protpcal) {  
  54.         this.protpcal = protpcal;  
  55.     }  
  56.   
  57.     public String getUserName() {  
  58.         return userName;  
  59.     }  
  60.   
  61.     public void setUserName(String userName) {  
  62.         this.userName = userName;  
  63.     }  
  64.   
  65.     public String getPassWord() {  
  66.         return passWord;  
  67.     }  
  68.   
  69.     public void setPassWord(String passWord) {  
  70.         this.passWord = passWord;  
  71.     }  
  72.   
  73.     public String getAttchmentDir() {  
  74.         return attchmentDir;  
  75.     }  
  76.   
  77.     public void setAttchmentDir(String attchmentDir) {  
  78.         if (!attchmentDir.endsWith(File.separator)) {  
  79.             attchmentDir = attchmentDir + File.separator;  
  80.         }  
  81.         this.attchmentDir = attchmentDir;  
  82.     }  
  83.   
  84.     public String getEmailDir() {  
  85.         return emailDir;  
  86.     }  
  87.   
  88.     public void setEmailDir(String emailDir) {  
  89.         if (!emailDir.endsWith(File.separator)) {  
  90.             emailDir = emailDir + File.separator;  
  91.         }  
  92.         this.emailDir = emailDir;  
  93.     }  
  94.   
  95.     public String getEmailFileSuffix() {  
  96.         return emailFileSuffix;  
  97.     }  
  98.   
  99.     public void setEmailFileSuffix(String emailFileSuffix) {  
  100.         if (!emailFileSuffix.endsWith(File.separator)) {  
  101.             emailFileSuffix = emailFileSuffix + File.separator;  
  102.         }  
  103.         this.emailFileSuffix = emailFileSuffix;  
  104.     }  
  105.   
  106.     public boolean isVaildate() {  
  107.         return vaildate;  
  108.     }  
  109.   
  110.     public void setVaildate(boolean vaildate) {  
  111.         this.vaildate = vaildate;  
  112.     }  
  113.   
  114. }  

  1. package com.skycn.pop3;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.ByteArrayOutputStream;  
  6. import java.io.File;  
  7. import java.io.FileWriter;  
  8. import java.io.IOException;  
  9. import java.io.InputStreamReader;  
  10. import java.io.Reader;  
  11. import java.io.StringReader;  
  12. import java.io.UnsupportedEncodingException;  
  13.   
  14. import javax.mail.BodyPart;  
  15. import javax.mail.Flags;  
  16. import javax.mail.Folder;  
  17. import javax.mail.Message;  
  18. import javax.mail.MessagingException;  
  19. import javax.mail.Multipart;  
  20. import javax.mail.NoSuchProviderException;  
  21. import javax.mail.Part;  
  22. import javax.mail.Session;  
  23. import javax.mail.Store;  
  24. import javax.mail.internet.InternetAddress;  
  25. import javax.mail.internet.MimeMessage;  
  26. import javax.mail.internet.MimeUtility;  
  27. import javax.xml.crypto.Data;  
  28.   
  29. import com.skycn.helper.MyAuthenticator;  
  30.   
  31. /******************************************************************************* 
  32.  * 邮件接收器,目前支持pop3协议 能够接受文本,html和带有福建的邮件 
  33.  *  
  34.  * @author tianzhw 
  35.  */  
  36. @SuppressWarnings("unused")  
  37. public class MailReceiver {  
  38.   
  39.     private MailReceiverInfo receiverInfo;// 邮件的参数配置   
  40.     private Store store;// 以邮件服务器连接后得到的邮箱   
  41.     private Folder folder;// 收件箱   
  42.     private Message[] messages;// 收件箱中的邮件消息   
  43.     private Message currentMessage;// 正在处理的邮件消息   
  44.     private String currentEmailFileName;  
  45.   
  46.     public MailReceiver(MailReceiverInfo receiverInfo) {  
  47.         this.receiverInfo = receiverInfo;  
  48.     }  
  49.   
  50.     /*************************************************************************** 
  51.      * 收邮件 
  52.      */  
  53.     public void receiveAllMail() throws Exception {  
  54.         if (this.receiverInfo == null) {  
  55.             throw new Exception("必须提供收邮件的参数");  
  56.         }  
  57.         // 打开连接   
  58.         if (this.connectToServer()) {  
  59.             // 打开收件箱   
  60.             if (this.openInBoxFolder()) {  
  61.                 // 收件箱里面的邮件信息输出   
  62.                 this.getAllMail();  
  63.                 this.closeConnection();  
  64.             } else {  
  65.                 throw new Exception("打开连接失败");  
  66.             }  
  67.         } else {  
  68.             throw new Exception("打开连接失败");  
  69.         }  
  70.   
  71.     }  
  72.   
  73.     /*************************************************************************** 
  74.      * 登录服务器,登录服务器,通过Session对象创建store对象。同时讲session对象中认证名和密码,协议描述,等信息通知服务器。 
  75.      */  
  76.     @SuppressWarnings("unused")  
  77.     private boolean connectToServer() {  
  78.         // 判断是否需要身份认证   
  79.         MyAuthenticator authenticator = null;  
  80.         if (this.receiverInfo.isVaildate()) {  
  81.             // 如果需要身份认证,则创建一个密码验证器   
  82.             authenticator = new MyAuthenticator(  
  83.                     this.receiverInfo.getUserName(), this.receiverInfo  
  84.                             .getPassWord());  
  85.         }  
  86.         // 创建一个session   
  87.         Session mailSession = Session.getInstance(this.receiverInfo  
  88.                 .getProperties());  
  89.         try {  
  90.             // 创建store,建立连接,通过Session对象是可以创建一个store对象的。   
  91.             this.store = mailSession.getStore(this.receiverInfo.getProtpcal());  
  92.         } catch (NoSuchProviderException e) {  
  93.             System.out.println("链接服务器失败");  
  94.             return false;  
  95.         }  
  96.         System.out.println("connecting");  
  97.         try {  
  98.             this.store.connect();  
  99.         } catch (MessagingException e) {  
  100.             // TODO Auto-generated catch block   
  101.             System.out.println("链接服务器失败");  
  102.             return false;  
  103.         }  
  104.         return true;  
  105.     }  
  106.   
  107.     /*************************************************************************** 
  108.      * 打开收件箱 
  109.      * stroe是一个邮箱的整体,如果连接上以后,我们有很多抽屉,Inbox是国际默认的收件箱(抽屉的)标示。但是也有不是这样的,这取决于什么邮件服务器 
  110.      */  
  111.     private boolean openInBoxFolder() {  
  112.         try {  
  113.             this.folder = this.store.getFolder("inbox");  
  114.             folder.open(Folder.READ_ONLY);  
  115.             return true;  
  116.         } catch (MessagingException e) {  
  117.             // TODO Auto-generated catch block   
  118.             e.printStackTrace();  
  119.         }  
  120.         return false;  
  121.     }  
  122.   
  123.     /*************************************************************************** 
  124.      * 关闭链接 
  125.      *  
  126.      * @return 
  127.      */  
  128.     private boolean closeConnection() {  
  129.         try {  
  130.             if (this.folder.isOpen()) {  
  131.                 this.folder.close(true);  
  132.             }  
  133.             this.store.close();  
  134.             System.out.println("关闭链接成功 ");  
  135.             return true;  
  136.         } catch (MessagingException e) {  
  137.             // TODO Auto-generated catch block   
  138.             e.printStackTrace();  
  139.         }  
  140.         return false;  
  141.     }  
  142.   
  143.     private void getAllMail() throws Exception {  
  144.         // 文件夹下获取邮件信息   
  145.         this.messages = this.folder.getMessages();  
  146.         System.out.println("总邮件数目:" + messages.length);  
  147.         System.out.println("新邮件数目:" + this.getNewMessageCount());  
  148.         System.out.println("未读邮件数目:" + this.getUnreadMessageConunt());  
  149.         // 将要下载的邮件数量   
  150.         int mailArrayLength = this.getMessageCount();  
  151.         System.out.println("一共有邮件" + mailArrayLength + "封");  
  152.         int errorCounter = 0;  
  153.         int successCounter = 0;  
  154.         for (int index = 0; index < mailArrayLength; index++) {  
  155.             this.currentMessage = messages[index];  
  156.             System.out.println("正在获取第" + index + "封邮件~~~~~~~~~~~~~~");  
  157.             this.showMailBasicInfo();  
  158.         }  
  159.   
  160.     }  
  161.   
  162.     private void showMailBasicInfo() throws Exception {  
  163.         // TODO Auto-generated method stub   
  164.         showMailBasicInfo(this.currentMessage);  
  165.     }  
  166.   
  167.     /*************************************************************************** 
  168.      * 显示邮件的基本信息 
  169.      *  
  170.      * @param message 
  171.      * @throws Exception 
  172.      */  
  173.     private void showMailBasicInfo(Message message) throws Exception {  
  174.         // TODO Auto-generated method stub   
  175.         System.out.println("~~~~~~~~~~~邮件ID:" + this.getMessageId()  
  176.                 + "~~~~~~~~~~~~~~~~~~~~~~~ ");  
  177.         System.out.println("From:" + this.getFrom());  
  178.         System.out.println("To:" + this.getToAddress());  
  179.         System.out.println("CC:" + this.getCCAddress());  
  180.         System.out.println("BCC:" + this.getBCCAddress());  
  181.         System.out.println("Subject:" + this.getSubject());  
  182.         System.out.println("发送时间:" + this.getSentDate());  
  183.         System.out.println("是新邮件?:" + this.isNew());  
  184.         System.out.println("是否回执:" + this.getReplySign());  
  185.         System.out.println("包涵附件:" + this.isContainAttch());  
  186.         System.out  
  187.                 .println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");  
  188.     }  
  189.   
  190.     private boolean isContainAttch() throws Exception {  
  191.         // TODO Auto-generated method stub   
  192.         return isContainAttch(this.currentMessage);  
  193.     }  
  194.   
  195.     /*************************************************************************** 
  196.      * 判断邮件是否是包含附件 
  197.      *  
  198.      * @param part 
  199.      * @return 
  200.      * @throws Exception 
  201.      */  
  202.     private boolean isContainAttch(Part part) throws Exception {  
  203.         boolean attachflag = false;  
  204.         if (part.isMimeType("multipart/*")) {  
  205.             // 如果邮件体包含多部分   
  206.             Multipart mp = (Multipart) part.getContent();  
  207.   
  208.             for (int i = 0; i < mp.getCount(); i++) {  
  209.                 BodyPart bodyPart = mp.getBodyPart(i);  
  210.                 String disposition = bodyPart.getDisposition();  
  211.                 if ((disposition != null)  
  212.                         && ((disposition.equals(Part.ATTACHMENT) || (disposition  
  213.                                 .equals(Part.INLINE))))) {  
  214.                     attachflag = true;  
  215.                 } else if (bodyPart.isMimeType("Multipart/*")) {  
  216.                     attachflag = isContainAttch((Part) bodyPart);  
  217.                 } else {  
  218.                     String contype = bodyPart.getContentType();  
  219.                     if (contype.toLowerCase().indexOf("applcation") != -1) {  
  220.                         attachflag = true;  
  221.                     }  
  222.                     if (contype.toLowerCase().indexOf("name") != -1) {  
  223.                         attachflag = true;  
  224.                     }  
  225.                 }  
  226.             }  
  227.         } else if (part.isMimeType("message/rfc822")) {  
  228.             attachflag = isContainAttch((Part) part.getContent());  
  229.         }  
  230.         return attachflag;  
  231.     }  
  232.   
  233.     private String getMessageId() throws Exception {  
  234.         // TODO Auto-generated method stub   
  235.         return getMessageId(this.currentMessage);  
  236.     }  
  237.   
  238.     /***************************************************************************  
  239.      * 获得Message - Id  
  240.      *   
  241.      * @param mimeMessage  
  242.      * @return  
  243.      * @throws Exception  
  244.      */  
  245.     private String getMessageId(Message mimeMessage) throws Exception {  
  246.         MimeMessage message = (MimeMessage) mimeMessage;  
  247.         return message.getMessageID();  
  248.     }  
  249.   
  250.     private boolean getReplySign() throws Exception {  
  251.         // TODO Auto-generated method stub   
  252.         return getReplySign(this.currentMessage);  
  253.     }  
  254.   
  255.     /*************************************************************************** 
  256.      * 判断邮件是否需要回执。 
  257.      *  
  258.      * @param mimeMessage 
  259.      * @return 
  260.      * @throws Exception 
  261.      */  
  262.     private boolean getReplySign(Message mimeMessage) throws Exception {  
  263.         // TODO Auto-generated method stub   
  264.         boolean replaysign = false;  
  265.         String[] needreply = (String[]) mimeMessage  
  266.                 .getHeader("Disposition-Notification-To");  
  267.         if (needreply != null) {  
  268.             replaysign = true;  
  269.         }  
  270.         return replaysign;  
  271.     }  
  272.   
  273.     private boolean isNew() throws Exception {  
  274.         // TODO Auto-generated method stub   
  275.         return isNew(this.currentMessage);  
  276.     }  
  277.   
  278.     /*************************************************************************** 
  279.      * 获得邮件是否是已经读过了 
  280.      *  
  281.      * @param mimeMessage 
  282.      * @return 
  283.      * @throws Exception 
  284.      */  
  285.     private boolean isNew(Message mimeMessage) throws Exception {  
  286.         // TODO Auto-generated method stub   
  287.         boolean isnew = false;  
  288.         Flags flags = mimeMessage.getFlags();  
  289.         Flags.Flag[] flag = flags.getSystemFlags();  
  290.         for (int i = 0; i < flag.length; i++) {  
  291.             if (flag[i] == Flags.Flag.SEEN) {  
  292.                 isnew = true;  
  293.                 break;  
  294.             }  
  295.         }  
  296.         return false;  
  297.     }  
  298.   
  299.     private Data getSentDate() throws Exception {  
  300.         // TODO Auto-generated method stub   
  301.         return getSetDate(this.currentMessage);  
  302.     }  
  303.   
  304.     /** 
  305.      * 获得邮件的发送日期 
  306.      *  
  307.      * @param mimeMessage 
  308.      * @return 
  309.      * @throws Exception 
  310.      */  
  311.     private Data getSetDate(Message mimeMessage) throws Exception {  
  312.         // TODO Auto-generated method stub   
  313.         return (Data) mimeMessage.getSentDate();  
  314.     }  
  315.   
  316.     /** 
  317.      * 获得邮件的发送主题 
  318.      *  
  319.      * @return 
  320.      * @throws Exception 
  321.      */  
  322.     private String getSubject() throws Exception {  
  323.         return getSubject(this.currentMessage);  
  324.     }  
  325.   
  326.     private String getSubject(Message mimeMessage) throws Exception {  
  327.         // TODO Auto-generated method stub   
  328.         String subject = "";  
  329.         try {  
  330.             subject = MimeUtility.decodeText(mimeMessage.getSubject());  
  331.             if (subject == null) {  
  332.                 subject = "";  
  333.             }  
  334.         } catch (Exception e) {  
  335.         }  
  336.         return subject;  
  337.     }  
  338.   
  339.     /*************************************************************************** 
  340.      * 获得发件人的地址和姓名 
  341.      *  
  342.      * @return 
  343.      * @throws Exception 
  344.      */  
  345.     private String getFrom() throws Exception {  
  346.         return getFrom(this.currentMessage);  
  347.     }  
  348.   
  349.     /*************************************************************************** 
  350.      * 获得发件人的地址和姓名 
  351.      *  
  352.      * @return 
  353.      * @throws Exception 
  354.      */  
  355.     private String getFrom(Message mimeMessage) throws Exception {  
  356.         InternetAddress[] address = (InternetAddress[]) mimeMessage.getFrom();  
  357.         // 获得发件人的邮件地址   
  358.         String from = address[0].getAddress();  
  359.         if (from == null) {  
  360.             from = "";  
  361.         }  
  362.         // 获得发件人的描述   
  363.         String personal = address[0].getPersonal();  
  364.         if (personal == null) {  
  365.             personal = "";  
  366.         }  
  367.         String fromaddr = personal + "<" + from + ">";  
  368.         return fromaddr;  
  369.     }  
  370.   
  371.     /** 
  372.      * 根据传递的参数的不同,获得邮件收件人、抄送、密送的地址和姓名 to---收件人 cc----抄送人 bcc----密送人 
  373.      *  
  374.      * @return 
  375.      * @throws Exception 
  376.      */  
  377.     private String getBCCAddress() throws Exception {  
  378.         // TODO Auto-generated method stub   
  379.         return getMailAddress("BCC"this.currentMessage);  
  380.     }  
  381.   
  382.     private String getCCAddress() throws Exception {  
  383.         // TODO Auto-generated method stub   
  384.         return getMailAddress("CC"this.currentMessage);  
  385.     }  
  386.   
  387.     private String getToAddress() throws Exception {  
  388.         // TODO Auto-generated method stub   
  389.         return getMailAddress("TO"this.currentMessage);  
  390.     }  
  391.   
  392.     /*************************************************************************** 
  393.      * 获得邮件地址 
  394.      *  
  395.      * @param type 
  396.      *            类型 如 收件人 抄送人 密送人 
  397.      * @param mimeMessage 
  398.      *            邮件消息 
  399.      * @return 
  400.      * @throws Exception 
  401.      */  
  402.     private String getMailAddress(String type, Message mimeMessage)  
  403.             throws Exception {  
  404.         String mailaddr = "";  
  405.         String addtype = type.toUpperCase();  
  406.         InternetAddress[] address = null;  
  407.         if (addtype.equals("TO") || addtype.equals("CC")  
  408.                 || addtype.equals("BCC")) {  
  409.             if (addtype.equals("TO")) {  
  410.                 address = (InternetAddress[]) mimeMessage  
  411.                         .getRecipients(Message.RecipientType.TO);  
  412.             }  
  413.             if (addtype.equals("CC")) {  
  414.                 address = (InternetAddress[]) mimeMessage  
  415.                         .getRecipients(Message.RecipientType.CC);  
  416.             }  
  417.             if (addtype.equals("BCC")) {  
  418.                 address = (InternetAddress[]) mimeMessage  
  419.                         .getRecipients(Message.RecipientType.BCC);  
  420.             }  
  421.             if (address != null) {  
  422.                 for (int i = 0; i < address.length; i++) {  
  423.                     // 先获取邮件地址   
  424.                     String email = address[i].getAddress();  
  425.                     if (email == null) {  
  426.                         email = "";  
  427.                     } else {  
  428.                         email = MimeUtility.decodeText(email);  
  429.                     }  
  430.                     // 再取得个人描述信息   
  431.                     String personal = address[i].getPersonal();  
  432.                     if (personal == null) {  
  433.                         personal = "";  
  434.                     } else {  
  435.                         personal = MimeUtility.decodeText(personal);  
  436.                     }  
  437.                     // 讲个人描述信息与邮件地址连接起来   
  438.                     String compostiteto = personal + "<" + email + ">";  
  439.                     // 多个地址用,号分隔   
  440.                     mailaddr += "," + compostiteto;  
  441.                 }  
  442.                 mailaddr = mailaddr.substring(1);  
  443.             }  
  444.         } else {  
  445.             throw new Exception("错误的地址类型");  
  446.         }  
  447.         return mailaddr;  
  448.     }  
  449.   
  450.     /*************************************************************************** 
  451.      * 获得messages中Message的个数 
  452.      *  
  453.      * @return 
  454.      */  
  455.     private int getMessageCount() {  
  456.         // TODO Auto-generated method stub   
  457.         return this.messages.length;  
  458.     }  
  459.   
  460.     /** 
  461.      * 获得邮件里面未读的邮件个数 
  462.      *  
  463.      * @return 
  464.      * @throws MessagingException 
  465.      */  
  466.     private int getUnreadMessageConunt() throws MessagingException {  
  467.         // TODO Auto-generated method stub   
  468.         return this.folder.getUnreadMessageCount();  
  469.     }  
  470.   
  471.     /** 
  472.      * 获得邮件里面新邮件的个数 
  473.      *  
  474.      * @return 
  475.      * @throws MessagingException 
  476.      */  
  477.     private int getNewMessageCount() throws MessagingException {  
  478.         // TODO Auto-generated method stub   
  479.         return this.folder.getNewMessageCount();  
  480.     }  
  481.   
  482.     /*************************************************************************** 
  483.      * 获得当前邮件 
  484.      *  
  485.      * @throws MessagingException 
  486.      * @throws IOException 
  487.      */  
  488.     private void getMail() throws Exception {  
  489.         this.saveMessageAsFile(this.currentMessage);  
  490.         this.parseMessage(this.currentMessage);  
  491.     }  
  492.   
  493.     /*************************************************************************** 
  494.      * 解析邮件 
  495.      *  
  496.      * @param currentMessage2 
  497.      * @throws MessagingException 
  498.      * @throws IOException 
  499.      */  
  500.     private void parseMessage(Message message) throws IOException,  
  501.             MessagingException {  
  502.         Object content = message.getContent();  
  503.         if (content instanceof Multipart) {  
  504.             handleMultipart((Multipart) content);  
  505.         } else {  
  506.             handlePart(message);  
  507.         }  
  508.   
  509.     }  
  510.   
  511.     /*************************************************************************** 
  512.      * 解析Multipart 
  513.      *  
  514.      * @param content 
  515.      * @throws MessagingException 
  516.      * @throws IOException 
  517.      */  
  518.     private void handleMultipart(Multipart multipart)  
  519.             throws MessagingException, IOException {  
  520.         for (int i = 0, n = multipart.getCount(); i < n; i++) {  
  521.             handlePart(multipart.getBodyPart(i));  
  522.         }  
  523.   
  524.     }  
  525.   
  526.     /*************************************************************************** 
  527.      *  
  528.      * @param bodyPart 
  529.      * @throws MessagingException 
  530.      * @throws IOException 
  531.      */  
  532.     private void handlePart(Part part) throws MessagingException, IOException {  
  533.         String dispostion = part.getDisposition();  
  534.         String contentType = part.getContentType();  
  535.         String fileNameWidthExtension = "";  
  536.         // 获得邮件的内容输入流   
  537.         InputStreamReader sbis = new InputStreamReader(part.getInputStream());  
  538.         // 在没有附件的情况   
  539.         if (dispostion == null) {  
  540.             if ((contentType.length() >= 10)  
  541.                     && (contentType.toLowerCase().substring(010)  
  542.                             .equals("text/plain"))) {  
  543.                 fileNameWidthExtension = this.receiverInfo.getAttchmentDir()  
  544.                         + this.currentEmailFileName + ".txt";  
  545.             } else if ((contentType.length() >= 9)  
  546.                     && (contentType.toLowerCase().substring(09)  
  547.                             .equals("text/html"))) {  
  548.                 fileNameWidthExtension = this.receiverInfo.getAttchmentDir()  
  549.                         + this.currentEmailFileName + ".html";  
  550.             } else if ((contentType.length() >= 9)  
  551.                     && (contentType.toLowerCase().substring(09)  
  552.                             .equals("text/gif"))) {  
  553.                 fileNameWidthExtension = this.receiverInfo.getAttchmentDir()  
  554.                         + this.currentEmailFileName + ".gif";  
  555.             } else if ((contentType.length() >= 9)  
  556.                     && (contentType.toLowerCase().substring(09)  
  557.                             .equals("multipart/*"))) {  
  558.                 handleMultipart((Multipart) part.getContent());  
  559.             } else {  
  560.                 fileNameWidthExtension = this.receiverInfo.getAttchmentDir()  
  561.                         + this.currentEmailFileName + ".txt";  
  562.             }  
  563.             System.out.println("保存邮件内容到:" + fileNameWidthExtension);  
  564.             saveFile(fileNameWidthExtension, sbis);  
  565.             return;  
  566.         }  
  567.         // 各种有附件的情况   
  568.         String name = "";  
  569.         if (dispostion.equalsIgnoreCase(Part.ATTACHMENT)) {  
  570.             name = getFileName(part);  
  571.             fileNameWidthExtension = this.receiverInfo.getAttchmentDir() + name;  
  572.         } else if (dispostion.equalsIgnoreCase(Part.INLINE)) {  
  573.             name = getFileName(part);  
  574.             fileNameWidthExtension = this.receiverInfo.getAttchmentDir() + name;  
  575.         } else {  
  576.   
  577.         }  
  578.   
  579.         // 储存各类附件   
  580.         if (!fileNameWidthExtension.equals("")) {  
  581.             System.out.println("保存邮件附件到:" + fileNameWidthExtension);  
  582.             saveFile(fileNameWidthExtension, sbis);  
  583.         }  
  584.   
  585.     }  
  586.   
  587.     private String getFileName(Part part) throws UnsupportedEncodingException,  
  588.             MessagingException {  
  589.         String fileName = part.getFileName();  
  590.         fileName = MimeUtility.decodeText(fileName);  
  591.         String name = fileName;  
  592.         if (fileName != null) {  
  593.             int index = fileName.lastIndexOf("/");  
  594.             if (index != -1) {  
  595.                 name = fileName.substring(index + 1);  
  596.             }  
  597.         }  
  598.         return name;  
  599.     }  
  600.   
  601.     /***************************************************************************  
  602.      * 保存邮件源文件  
  603.      *   
  604.      * @param currentMessage2  
  605.      */  
  606.     private void saveMessageAsFile(Message message) {  
  607.         try {  
  608.             // 将邮件ID中尖括号中的部分作为邮件的文件名   
  609.             String oriFileName = getInfoBetweenBrackets(this.getMessageId(  
  610.                     message).toString());  
  611.             // 设置文件后缀名,如是附件则设法取得其文件后缀名作为将要保存文件的后缀名。如是正文不封则用。html作为后缀名   
  612.             String emlName = oriFileName;  
  613.             String fileNameWidthExtension = this.receiverInfo.getEmailDir()  
  614.                     + oriFileName + this.receiverInfo.getEmailFileSuffix();  
  615.             File storeFile = new File(fileNameWidthExtension);  
  616.             for (int i = 0; storeFile.exists(); i++) {  
  617.                 emlName = oriFileName + i;  
  618.                 fileNameWidthExtension = this.receiverInfo.getEmailDir()  
  619.                         + emlName + this.receiverInfo.getEmailFileSuffix();  
  620.                 storeFile = new File(fileNameWidthExtension);  
  621.             }  
  622.             this.currentEmailFileName = emlName;  
  623.             System.out.println("邮件消息的存储路径:" + fileNameWidthExtension);  
  624.             // 将邮件消息的内容写入ByteArrayOutputStram流中   
  625.             ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  626.             message.writeTo(baos);  
  627.             StringReader in = new StringReader(baos.toString());  
  628.             saveFile(fileNameWidthExtension, in);  
  629.   
  630.         } catch (Exception e) {  
  631.             // TODO Auto-generated catch block   
  632.             e.printStackTrace();  
  633.         }  
  634.   
  635.     }  
  636.   
  637.     /** 
  638.      * 保存文件内容 
  639.      *  
  640.      * @param fileName 
  641.      * @param in 
  642.      * @throws IOException 
  643.      */  
  644.     private void saveFile(String fileName, Reader in) throws IOException {  
  645.         // 为了防止文件名重名,在重名的文件后面添加上数字   
  646.         File file = new File(fileName);  
  647.         // 先取得文件名的后缀   
  648.         int lastDot = fileName.lastIndexOf(".");  
  649.         String extension = fileName.substring(lastDot);  
  650.         fileName = fileName.substring(0, lastDot);  
  651.         for (int i = 0; file.exists(); i++) {  
  652.             file = new File(fileName + i + extension);  
  653.         }  
  654.         // 从输入流中读取数据,写入文件的输入流   
  655.         FileWriter fos = new FileWriter(file);  
  656.         BufferedWriter bos = new BufferedWriter(fos);  
  657.         BufferedReader bis = new BufferedReader(in);  
  658.         int aByte;  
  659.         while ((aByte = bis.read()) != -1) {  
  660.             bos.write(aByte);  
  661.         }  
  662.         bos.flush();  
  663.         bos.close();  
  664.         bis.close();  
  665.     }  
  666.   
  667.     /** 
  668.      * 获得尖括号之间的字符串 如 tianzhw <tianzhw@vip.qq.com> ----- tianzhw@vip.qq.cpm 
  669.      *  
  670.      * @param string 
  671.      * @return 
  672.      */  
  673.     private String getInfoBetweenBrackets(String str) {  
  674.         int i, j;  
  675.         if (str == null) {  
  676.             str = "error";  
  677.             return str;  
  678.         }  
  679.         i = str.lastIndexOf("<");  
  680.         j = str.lastIndexOf(">");  
  681.         if (i != 1 && j != -1) {  
  682.             str = str.substring(i + 1, j);  
  683.         }  
  684.         return str;  
  685.     }  
  686.   
  687.     public static void main(String[] args) throws Exception {  
  688.         MailReceiverInfo info = new MailReceiverInfo();  
  689.         info.setMailServerHost("pop.163.com");  
  690.         info.setMailServerPost("110");  
  691.         info.setVaildate(true);  
  692.         info.setUserName("*************");  
  693.         info.setPassWord("*************");  
  694.         info.setAttchmentDir("F:/mails");  
  695.         info.setEmailDir("F:/mails");  
  696.           
  697.         MailReceiver receiver = new MailReceiver(info);  
  698.           
  699.         receiver.receiveAllMail();  
  700.     }  
  701. }  
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
用java收邮件
HttpClient工具类
聊聊rocketmq的LitePullConsumer
POI3.5读取Excel2007
一步一步android(15):关于socket编程【以聊天为例】_目睹一个Geek的生活...
《Java Web应用程序开发》02 IO流
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服