[Java] java邮件接收器 pop3协议 →→→→→进入此内容的聊天室

来自 , 2021-02-25, 写在 Java, 查看 111 次.
URL http://www.code666.cn/view/3a077244
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.io.Reader;
  9. import java.io.StringReader;
  10. import java.io.UnsupportedEncodingException;
  11. import java.util.Date;
  12.  
  13. import javax.mail.Authenticator;
  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.PasswordAuthentication;
  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.MimeUtility;
  28.  
  29. import java.util.Properties;
  30.  
  31. /**
  32.  * 邮件接收器,目前支持pop3协议。 能够接收文本、HTML和带有附件的邮件
  33.  *
  34.  * 需要导入mail.jar
  35.  */
  36. public class MailReceiver {
  37.         // 收邮件的参数配置
  38.         private MailReceiverInfo receiverInfo;
  39.         // 与邮件服务器连接后得到的邮箱
  40.         private Store store;
  41.         // 收件箱
  42.         private Folder folder;
  43.         // 收件箱中的邮件消息
  44.         private Message[] messages;
  45.         // 当前正在处理的邮件消息
  46.         private Message currentMessage;
  47.  
  48.         private String currentEmailFileName;
  49.  
  50.         public MailReceiver(MailReceiverInfo receiverInfo) {
  51.                 this.receiverInfo = receiverInfo;
  52.         }
  53.  
  54.         /**
  55.          * 收邮件
  56.          */
  57.         public void receiveAllMail() throws Exception {
  58.                 if (this.receiverInfo == null) {
  59.                         throw new Exception("必须提供接收邮件的参数!");
  60.                 }
  61.                 // 连接到服务器
  62.                 if (this.connectToServer()) {
  63.                         // 打开收件箱
  64.                         if (this.openInBoxFolder()) {
  65.                                 // 获取所有邮件
  66.                                 this.getAllMail();
  67.                                 this.closeConnection();
  68.                         } else {
  69.                                 throw new Exception("打开收件箱失败!");
  70.                         }
  71.                 } else {
  72.                         throw new Exception("连接邮件服务器失败!");
  73.                 }
  74.         }
  75.  
  76.         /**
  77.          * 登陆邮件服务器
  78.          */
  79.         private boolean connectToServer() {
  80.                 // 判断是否需要身份认证
  81.                 MyAuthenticator authenticator = null;
  82.                 if (this.receiverInfo.isValidate()) {
  83.                         // 如果需要身份认证,则创建一个密码验证器
  84.                         authenticator = new MyAuthenticator(
  85.                                         this.receiverInfo.getUserName(),
  86.                                         this.receiverInfo.getPassword());
  87.                 }
  88.                 // 创建session
  89.                 Session session = Session.getInstance(
  90.                                 this.receiverInfo.getProperties(), authenticator);
  91.  
  92.                 // 创建store,建立连接
  93.                 try {
  94.                         this.store = session.getStore(this.receiverInfo.getProtocal());
  95.                 } catch (NoSuchProviderException e) {
  96.                         System.out.println("连接服务器失败!");
  97.                         return false;
  98.                 }
  99.  
  100.                 System.out.println("connecting");
  101.                 try {
  102.                         this.store.connect();
  103.                 } catch (MessagingException e) {
  104.                         System.out.println("连接服务器失败!");
  105.                         return false;
  106.                 }
  107.                 System.out.println("连接服务器成功");
  108.                 return true;
  109.         }
  110.  
  111.         /**
  112.          * 打开收件箱
  113.          */
  114.         private boolean openInBoxFolder() {
  115.                 try {
  116.                         this.folder = store.getFolder("INBOX");
  117.                         // 只读
  118.                         folder.open(Folder.READ_ONLY);
  119.                         return true;
  120.                 } catch (MessagingException e) {
  121.                         System.err.println("打开收件箱失败!");
  122.                 }
  123.                 return false;
  124.         }
  125.  
  126.         /**
  127.          * 断开与邮件服务器的连接
  128.          */
  129.         private boolean closeConnection() {
  130.                 try {
  131.                         if (this.folder.isOpen()) {
  132.                                 this.folder.close(true);
  133.                         }
  134.                         this.store.close();
  135.                         System.out.println("成功关闭与邮件服务器的连接!");
  136.                         return true;
  137.                 } catch (Exception e) {
  138.                         System.out.println("关闭和邮件服务器之间连接时出错!");
  139.                 }
  140.                 return false;
  141.         }
  142.  
  143.         /**
  144.          * 获取messages中的所有邮件
  145.          *
  146.          * @throws MessagingException
  147.          */
  148.         private void getAllMail() throws MessagingException {
  149.                 // 从邮件文件夹获取邮件信息
  150.                 this.messages = this.folder.getMessages();
  151.                 System.out.println("总的邮件数目:" + messages.length);
  152.                 System.out.println("新邮件数目:" + this.getNewMessageCount());
  153.                 System.out.println("未读邮件数目:" + this.getUnreadMessageCount());
  154.                 // 将要下载的邮件的数量。
  155.                 int mailArrayLength = this.getMessageCount();
  156.                 System.out.println("一共有邮件" + mailArrayLength + "封");
  157.                 int errorCounter = 0; // 邮件下载出错计数器
  158.                 int successCounter = 0;
  159.                 for (int index = 0; index < mailArrayLength; index++) {
  160.                         try {
  161.                                 this.currentMessage = (messages[index]); // 设置当前message
  162.                                 System.out.println("正在获取第" + index + "封邮件......");
  163.                                 this.showMailBasicInfo();
  164.                                 getMail(); // 获取当前message
  165.                                 System.out.println("成功获取第" + index + "封邮件");
  166.                                 successCounter++;
  167.                         } catch (Throwable e) {
  168.                                 errorCounter++;
  169.                                 System.err.println("下载第" + index + "封邮件时出错");
  170.                         }
  171.                 }
  172.                 System.out.println("------------------");
  173.                 System.out.println("成功下载了" + successCounter + "封邮件");
  174.                 System.out.println("失败下载了" + errorCounter + "封邮件");
  175.                 System.out.println("------------------");
  176.         }
  177.  
  178.         /**
  179.          * 显示邮件的基本信息
  180.          */
  181.         private void showMailBasicInfo() throws Exception {
  182.                 showMailBasicInfo(this.currentMessage);
  183.         }
  184.  
  185.         private void showMailBasicInfo(Message message) throws Exception {
  186.                 System.out.println("-------- 邮件ID:" + this.getMessageId()
  187.                                 + " ---------");
  188.                 System.out.println("From:" + this.getFrom());
  189.                 System.out.println("To:" + this.getTOAddress());
  190.                 System.out.println("CC:" + this.getCCAddress());
  191.                 System.out.println("BCC:" + this.getBCCAddress());
  192.                 System.out.println("Subject:" + this.getSubject());
  193.                 System.out.println("发送时间::" + this.getSentDate());
  194.                 System.out.println("是新邮件?" + this.isNew());
  195.                 System.out.println("要求回执?" + this.getReplySign());
  196.                 System.out.println("包含附件?" + this.isContainAttach());
  197.                 System.out.println("------------------------------");
  198.         }
  199.  
  200.         /**
  201.          * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
  202.          */
  203.         private String getTOAddress() throws Exception {
  204.                 return getMailAddress("TO", this.currentMessage);
  205.         }
  206.  
  207.         private String getCCAddress() throws Exception {
  208.                 return getMailAddress("CC", this.currentMessage);
  209.         }
  210.  
  211.         private String getBCCAddress() throws Exception {
  212.                 return getMailAddress("BCC", this.currentMessage);
  213.         }
  214.  
  215.         /**
  216.          * 获得邮件地址
  217.          *
  218.          * @param type
  219.          *            类型,如收件人、抄送人、密送人
  220.          * @param mimeMessage
  221.          *            邮件消息
  222.          * @return
  223.          * @throws Exception
  224.          */
  225.         private String getMailAddress(String type, Message mimeMessage)
  226.                         throws Exception {
  227.                 String mailaddr = "";
  228.                 String addtype = type.toUpperCase();
  229.                 InternetAddress[] address = null;
  230.                 if (addtype.equals("TO") || addtype.equals("CC")
  231.                                 || addtype.equals("BCC")) {
  232.                         if (addtype.equals("TO")) {
  233.                                 address = (InternetAddress[]) mimeMessage
  234.                                                 .getRecipients(Message.RecipientType.TO);
  235.                         } else if (addtype.equals("CC")) {
  236.                                 address = (InternetAddress[]) mimeMessage
  237.                                                 .getRecipients(Message.RecipientType.CC);
  238.                         } else {
  239.                                 address = (InternetAddress[]) mimeMessage
  240.                                                 .getRecipients(Message.RecipientType.BCC);
  241.                         }
  242.                         if (address != null) {
  243.                                 for (int i = 0; i < address.length; i++) {
  244.                                         // 先获取邮件地址
  245.                                         String email = address[i].getAddress();
  246.                                         if (email == null) {
  247.                                                 email = "";
  248.                                         } else {
  249.                                                 email = MimeUtility.decodeText(email);
  250.                                         }
  251.                                         // 再取得个人描述信息
  252.                                         String personal = address[i].getPersonal();
  253.                                         if (personal == null) {
  254.                                                 personal = "";
  255.                                         } else {
  256.                                                 personal = MimeUtility.decodeText(personal);
  257.                                         }
  258.                                         // 将个人描述信息与邮件地址连起来
  259.                                         String compositeto = personal + "<" + email + ">";
  260.                                         // 多个地址时,用逗号分开
  261.                                         mailaddr += "," + compositeto;
  262.                                 }
  263.                                 mailaddr = mailaddr.substring(1);
  264.                         }
  265.                 } else {
  266.                         throw new Exception("错误的地址类型!!");
  267.                 }
  268.                 return mailaddr;
  269.         }
  270.  
  271.         /**
  272.          * 获得发件人的地址和姓名
  273.          *
  274.          * @throws Exception
  275.          */
  276.         private String getFrom() throws Exception {
  277.                 return getFrom(this.currentMessage);
  278.         }
  279.  
  280.         private String getFrom(Message mimeMessage) throws Exception {
  281.                 InternetAddress[] address = (InternetAddress[]) mimeMessage.getFrom();
  282.                 // 获得发件人的邮箱
  283.                 String from = address[0].getAddress();
  284.                 if (from == null) {
  285.                         from = "";
  286.                 }
  287.                 // 获得发件人的描述信息
  288.                 String personal = address[0].getPersonal();
  289.                 if (personal == null) {
  290.                         personal = "";
  291.                 }
  292.                 // 拼成发件人完整信息
  293.                 String fromaddr = personal + "<" + from + ">";
  294.                 return fromaddr;
  295.         }
  296.  
  297.         /**
  298.          * 获取messages中message的数量
  299.          *
  300.          * @return
  301.          */
  302.         private int getMessageCount() {
  303.                 return this.messages.length;
  304.         }
  305.  
  306.         /**
  307.          * 获得收件箱中新邮件的数量
  308.          *
  309.          * @return
  310.          * @throws MessagingException
  311.          */
  312.         private int getNewMessageCount() throws MessagingException {
  313.                 return this.folder.getNewMessageCount();
  314.         }
  315.  
  316.         /**
  317.          * 获得收件箱中未读邮件的数量
  318.          *
  319.          * @return
  320.          * @throws MessagingException
  321.          */
  322.         private int getUnreadMessageCount() throws MessagingException {
  323.                 return this.folder.getUnreadMessageCount();
  324.         }
  325.  
  326.         /**
  327.          * 获得邮件主题
  328.          */
  329.         private String getSubject() throws MessagingException {
  330.                 return getSubject(this.currentMessage);
  331.         }
  332.  
  333.         private String getSubject(Message mimeMessage) throws MessagingException {
  334.                 String subject = "";
  335.                 try {
  336.                         // 将邮件主题解码
  337.                         subject = MimeUtility.decodeText(mimeMessage.getSubject());
  338.                         if (subject == null) {
  339.                                 subject = "";
  340.                         }
  341.                 } catch (Exception exce) {
  342.                 }
  343.                 return subject;
  344.         }
  345.  
  346.         /**
  347.          * 获得邮件发送日期
  348.          */
  349.         private Date getSentDate() throws Exception {
  350.                 return getSentDate(this.currentMessage);
  351.         }
  352.  
  353.         private Date getSentDate(Message mimeMessage) throws Exception {
  354.                 return mimeMessage.getSentDate();
  355.         }
  356.  
  357.         /**
  358.          * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
  359.          */
  360.         private boolean getReplySign() throws MessagingException {
  361.                 return getReplySign(this.currentMessage);
  362.         }
  363.  
  364.         private boolean getReplySign(Message mimeMessage) throws MessagingException {
  365.                 boolean replysign = false;
  366.                 String needreply[] = mimeMessage
  367.                                 .getHeader("Disposition-Notification-To");
  368.                 if (needreply != null) {
  369.                         replysign = true;
  370.                 }
  371.                 return replysign;
  372.         }
  373.  
  374.         /**
  375.          * 获得此邮件的Message-ID
  376.          */
  377.         private String getMessageId() throws MessagingException {
  378.                 return getMessageId(this.currentMessage);
  379.         }
  380.  
  381.         private String getMessageId(Message mimeMessage) throws MessagingException {
  382.                 return ((MimeMessage) mimeMessage).getMessageID();
  383.         }
  384.  
  385.         /**
  386.          * 判断此邮件是否已读,如果未读返回返回false,反之返回true
  387.          */
  388.         private boolean isNew() throws MessagingException {
  389.                 return isNew(this.currentMessage);
  390.         }
  391.  
  392.         private boolean isNew(Message mimeMessage) throws MessagingException {
  393.                 boolean isnew = false;
  394.                 Flags flags = mimeMessage.getFlags();
  395.                 Flags.Flag[] flag = flags.getSystemFlags();
  396.                 for (int i = 0; i < flag.length; i++) {
  397.                         if (flag[i] == Flags.Flag.SEEN) {
  398.                                 isnew = true;
  399.                                 break;
  400.                         }
  401.                 }
  402.                 return isnew;
  403.         }
  404.  
  405.         /**
  406.          * 判断此邮件是否包含附件
  407.          */
  408.         private boolean isContainAttach() throws Exception {
  409.                 return isContainAttach(this.currentMessage);
  410.         }
  411.  
  412.         private boolean isContainAttach(Part part) throws Exception {
  413.                 boolean attachflag = false;
  414.                 if (part.isMimeType("multipart/*")) {
  415.                         // 如果邮件体包含多部分
  416.                         Multipart mp = (Multipart) part.getContent();
  417.                         // 遍历每部分
  418.                         for (int i = 0; i < mp.getCount(); i++) {
  419.                                 // 获得每部分的主体
  420.                                 BodyPart bodyPart = mp.getBodyPart(i);
  421.                                 String disposition = bodyPart.getDisposition();
  422.                                 if ((disposition != null)
  423.                                                 && ((disposition.equals(Part.ATTACHMENT)) || (disposition
  424.                                                                 .equals(Part.INLINE)))) {
  425.                                         attachflag = true;
  426.                                 } else if (bodyPart.isMimeType("multipart/*")) {
  427.                                         attachflag = isContainAttach((Part) bodyPart);
  428.                                 } else {
  429.                                         String contype = bodyPart.getContentType();
  430.                                         if (contype.toLowerCase().indexOf("application") != -1) {
  431.                                                 attachflag = true;
  432.                                         }
  433.                                         if (contype.toLowerCase().indexOf("name") != -1) {
  434.                                                 attachflag = true;
  435.                                         }
  436.                                 }
  437.                         }
  438.                 } else if (part.isMimeType("message/rfc822")) {
  439.                         attachflag = isContainAttach((Part) part.getContent());
  440.                 }
  441.                 return attachflag;
  442.         }
  443.  
  444.         /**
  445.          * 获得当前邮件
  446.          */
  447.         private void getMail() throws Exception {
  448.                 try {
  449.                         this.saveMessageAsFile(currentMessage);
  450.                         this.parseMessage(currentMessage);
  451.                 } catch (IOException e) {
  452.                         throw new IOException("保存邮件出错,检查保存路径");
  453.                 } catch (MessagingException e) {
  454.                         throw new MessagingException("邮件转换出错");
  455.                 } catch (Exception e) {
  456.                         e.printStackTrace();
  457.                         throw new Exception("未知错误");
  458.                 }
  459.         }
  460.  
  461.         /**
  462.          * 保存邮件源文件
  463.          */
  464.         private void saveMessageAsFile(Message message) {
  465.                 try {
  466.                         // 将邮件的ID中尖括号中的部分做为邮件的文件名
  467.                         String oriFileName = getInfoBetweenBrackets(this.getMessageId(
  468.                                         message).toString());
  469.                         // 设置文件后缀名。若是附件则设法取得其文件后缀名作为将要保存文件的后缀名,
  470.                         // 若是正文部分则用.htm做后缀名
  471.                         String emlName = oriFileName;
  472.                         String fileNameWidthExtension = this.receiverInfo.getEmailDir()
  473.                                         + oriFileName + this.receiverInfo.getEmailFileSuffix();
  474.                         File storeFile = new File(fileNameWidthExtension);
  475.                         for (int i = 0; storeFile.exists(); i++) {
  476.                                 emlName = oriFileName + i;
  477.                                 fileNameWidthExtension = this.receiverInfo.getEmailDir()
  478.                                                 + emlName + this.receiverInfo.getEmailFileSuffix();
  479.                                 storeFile = new File(fileNameWidthExtension);
  480.                         }
  481.                         this.currentEmailFileName = emlName;
  482.                         System.out.println("邮件消息的存储路径: " + fileNameWidthExtension);
  483.                         // 将邮件消息的内容写入ByteArrayOutputStream流中
  484.                         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  485.                         message.writeTo(baos);
  486.                         // 读取邮件消息流中的数据
  487.                         StringReader in = new StringReader(baos.toString());
  488.                         // 存储到文件
  489.                         saveFile(fileNameWidthExtension, in);
  490.                 } catch (MessagingException e) {
  491.                         e.printStackTrace();
  492.                 } catch (Exception e) {
  493.                         e.printStackTrace();
  494.                 }
  495.         }
  496.  
  497.         /*
  498.          * 解析邮件
  499.          */
  500.         private void parseMessage(Message message) throws IOException,
  501.                         MessagingException {
  502.                 Object content = message.getContent();
  503.                 // 处理多部分邮件
  504.                 if (content instanceof Multipart) {
  505.                         handleMultipart((Multipart) content);
  506.                 } else {
  507.                         handlePart(message);
  508.                 }
  509.         }
  510.  
  511.         /*
  512.          * 解析Multipart
  513.          */
  514.         private void handleMultipart(Multipart multipart)
  515.                         throws MessagingException, IOException {
  516.                 for (int i = 0, n = multipart.getCount(); i < n; i++) {
  517.                         handlePart(multipart.getBodyPart(i));
  518.                 }
  519.         }
  520.  
  521.         /*
  522.          * 解析指定part,从中提取文件
  523.          */
  524.         private void handlePart(Part part) throws MessagingException, IOException {
  525.                 String disposition = part.getDisposition();
  526.                 String contentType = part.getContentType();
  527.                 String fileNameWidthExtension = "";
  528.                 // 获得邮件的内容输入流
  529.                 InputStreamReader sbis = new InputStreamReader(part.getInputStream());
  530.                 // 没有附件的情况
  531.                 if (disposition == null) {
  532.                         if ((contentType.length() >= 10)
  533.                                         && (contentType.toLowerCase().substring(0, 10)
  534.                                                         .equals("text/plain"))) {
  535.                                 fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
  536.                                                 + this.currentEmailFileName + ".txt";
  537.                         } else if ((contentType.length() >= 9) // Check if html
  538.                                         && (contentType.toLowerCase().substring(0, 9)
  539.                                                         .equals("text/html"))) {
  540.                                 fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
  541.                                                 + this.currentEmailFileName + ".html";
  542.                         } else if ((contentType.length() >= 9) // Check if html
  543.                                         && (contentType.toLowerCase().substring(0, 9)
  544.                                                         .equals("image/gif"))) {
  545.                                 fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
  546.                                                 + this.currentEmailFileName + ".gif";
  547.                         } else if ((contentType.length() >= 11)
  548.                                         && contentType.toLowerCase().substring(0, 11)
  549.                                                         .equals("multipart/*")) {
  550.                                 // System.out.println("multipart body: " + contentType);
  551.                                 handleMultipart((Multipart) part.getContent());
  552.                         } else { // Unknown type
  553.                                 // System.out.println("Other body: " + contentType);
  554.                                 fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
  555.                                                 + this.currentEmailFileName + ".txt";
  556.                         }
  557.                         // 存储内容文件
  558.                         System.out.println("保存邮件内容到:" + fileNameWidthExtension);
  559.                         saveFile(fileNameWidthExtension, sbis);
  560.  
  561.                         return;
  562.                 }
  563.  
  564.                 // 各种有附件的情况
  565.                 String name = "";
  566.                 if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
  567.                         name = getFileName(part);
  568.                         // System.out.println("Attachment: " + name + " : "
  569.                         // + contentType);
  570.                         fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
  571.                                         + name;
  572.                 } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
  573.                         name = getFileName(part);
  574.                         // System.out.println("Inline: " + name + " : "
  575.                         // + contentType);
  576.                         fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
  577.                                         + name;
  578.                 } else {
  579.                         // System.out.println("Other: " + disposition);
  580.                 }
  581.                 // 存储各类附件
  582.                 if (!fileNameWidthExtension.equals("")) {
  583.                         System.out.println("保存邮件附件到:" + fileNameWidthExtension);
  584.                         saveFile(fileNameWidthExtension, sbis);
  585.                 }
  586.         }
  587.  
  588.         private String getFileName(Part part) throws MessagingException,
  589.                         UnsupportedEncodingException {
  590.                 String fileName = part.getFileName();
  591.                 fileName = MimeUtility.decodeText(fileName);
  592.                 String name = fileName;
  593.                 if (fileName != null) {
  594.                         int index = fileName.lastIndexOf("/");
  595.                         if (index != -1) {
  596.                                 name = fileName.substring(index + 1);
  597.                         }
  598.                 }
  599.                 return name;
  600.         }
  601.  
  602.         /**
  603.          * 保存文件内容
  604.          *
  605.          * @param fileName
  606.          *            文件名
  607.          * @param input
  608.          *            输入流
  609.          * @throws IOException
  610.          */
  611.         private void saveFile(String fileName, Reader input) throws IOException {
  612.  
  613.                 // 为了放置文件名重名,在重名的文件名后面天上数字
  614.                 File file = new File(fileName);
  615.                 // 先取得文件名的后缀
  616.                 int lastDot = fileName.lastIndexOf(".");
  617.                 String extension = fileName.substring(lastDot);
  618.                 fileName = fileName.substring(0, lastDot);
  619.                 for (int i = 0; file.exists(); i++) {
  620.                         //  如果文件重名,则添加i
  621.                         file = new File(fileName + i + extension);
  622.                 }
  623.                 // 从输入流中读取数据,写入文件输出流
  624.                 FileWriter fos = new FileWriter(file);
  625.                 BufferedWriter bos = new BufferedWriter(fos);
  626.                 BufferedReader bis = new BufferedReader(input);
  627.                 int aByte;
  628.                 while ((aByte = bis.read()) != -1) {
  629.                         bos.write(aByte);
  630.                 }
  631.                 // 关闭流
  632.                 bos.flush();
  633.                 bos.close();
  634.                 bis.close();
  635.         }
  636.  
  637.         /**
  638.          * 获得尖括号之间的字符
  639.          *
  640.          * @param str
  641.          * @return
  642.          * @throws Exception
  643.          */
  644.         private String getInfoBetweenBrackets(String str) throws Exception {
  645.                 int i, j; // 用于标识字符串中的"<"和">"的位置
  646.                 if (str == null) {
  647.                         str = "error";
  648.                         return str;
  649.                 }
  650.                 i = str.lastIndexOf("<");
  651.                 j = str.lastIndexOf(">");
  652.                 if (i != -1 && j != -1) {
  653.                         str = str.substring(i + 1, j);
  654.                 }
  655.                 return str;
  656.         }
  657.  
  658.         public static void main(String[] args) throws Exception {
  659.                 MailReceiverInfo receiverInfo = new MailReceiverInfo();
  660.                 receiverInfo.setMailServerHost("pop.163.com");
  661.                 receiverInfo.setMailServerPort("110");
  662.                 receiverInfo.setValidate(true);
  663.                 receiverInfo.setUserName("***");
  664.                 receiverInfo.setPassword("***");
  665.                 receiverInfo.setAttachmentDir("C:/temp/mail/");
  666.                 receiverInfo.setEmailDir("C:/temp/mail/");
  667.  
  668.                 MailReceiver receiver = new MailReceiver(receiverInfo);
  669.                 receiver.receiveAllMail();
  670.         }
  671. }
  672.  
  673. /**
  674.  * 收邮件的基本信息
  675.  */
  676. class MailReceiverInfo {
  677.         // 邮件服务器的IP、端口和协议
  678.         private String mailServerHost;
  679.         private String mailServerPort = "110";
  680.         private String protocal = "pop3";
  681.         // 登陆邮件服务器的用户名和密码
  682.         private String userName;
  683.         private String password;
  684.         // 保存邮件的路径
  685.         private String attachmentDir = "C:/temp/";
  686.         private String emailDir = "C:/temp/";
  687.         private String emailFileSuffix = ".eml";
  688.         // 是否需要身份验证
  689.         private boolean validate = true;
  690.  
  691.         /**
  692.          * 获得邮件会话属性
  693.          */
  694.         public Properties getProperties() {
  695.                 Properties p = new Properties();
  696.                 p.put("mail.pop3.host", this.mailServerHost);
  697.                 p.put("mail.pop3.port", this.mailServerPort);
  698.                 p.put("mail.pop3.auth", validate ? "true" : "false");
  699.                 return p;
  700.         }
  701.  
  702.         public String getProtocal() {
  703.                 return protocal;
  704.         }
  705.  
  706.         public void setProtocal(String protocal) {
  707.                 this.protocal = protocal;
  708.         }
  709.  
  710.         public String getAttachmentDir() {
  711.                 return attachmentDir;
  712.         }
  713.  
  714.         public void setAttachmentDir(String attachmentDir) {
  715.                 if (!attachmentDir.endsWith(File.separator)) {
  716.                         attachmentDir = attachmentDir + File.separator;
  717.                 }
  718.                 this.attachmentDir = attachmentDir;
  719.         }
  720.  
  721.         public String getEmailDir() {
  722.                 return emailDir;
  723.         }
  724.  
  725.         public void setEmailDir(String emailDir) {
  726.                 if (!emailDir.endsWith(File.separator)) {
  727.                         emailDir = emailDir + File.separator;
  728.                 }
  729.                 this.emailDir = emailDir;
  730.         }
  731.  
  732.         public String getEmailFileSuffix() {
  733.                 return emailFileSuffix;
  734.         }
  735.  
  736.         public void setEmailFileSuffix(String emailFileSuffix) {
  737.                 if (!emailFileSuffix.startsWith(".")) {
  738.                         emailFileSuffix = "." + emailFileSuffix;
  739.                 }
  740.                 this.emailFileSuffix = emailFileSuffix;
  741.         }
  742.  
  743.         public String getMailServerHost() {
  744.                 return mailServerHost;
  745.         }
  746.  
  747.         public void setMailServerHost(String mailServerHost) {
  748.                 this.mailServerHost = mailServerHost;
  749.         }
  750.  
  751.         public String getMailServerPort() {
  752.                 return mailServerPort;
  753.         }
  754.  
  755.         public void setMailServerPort(String mailServerPort) {
  756.                 this.mailServerPort = mailServerPort;
  757.         }
  758.  
  759.         public String getPassword() {
  760.                 return password;
  761.         }
  762.  
  763.         public void setPassword(String password) {
  764.                 this.password = password;
  765.         }
  766.  
  767.         public String getUserName() {
  768.                 return userName;
  769.         }
  770.  
  771.         public void setUserName(String userName) {
  772.                 this.userName = userName;
  773.         }
  774.  
  775.         public boolean isValidate() {
  776.                 return validate;
  777.         }
  778.  
  779.         public void setValidate(boolean validate) {
  780.                 this.validate = validate;
  781.         }
  782.  
  783. }
  784.  
  785. /**
  786.  * 邮件身份认证器,在发送邮件时使用
  787.  */
  788. class MyAuthenticator extends Authenticator {
  789.         // 登陆发送邮件服务器的用户名
  790.         private String userName;
  791.         // 登陆发送邮件服务器的密码
  792.         private String password;
  793.  
  794.         public MyAuthenticator(String userName, String password) {
  795.                 this.userName = userName;
  796.                 this.password = password;
  797.         }
  798.  
  799.         /**
  800.          * 覆盖父类的该方法,获得密码认证器
  801.          */
  802.         protected PasswordAuthentication getPasswordAuthentication() {
  803.                 return new PasswordAuthentication(userName, password);
  804.         }
  805.  
  806.         public String getPassword() {
  807.                 return password;
  808.         }
  809.  
  810.         public void setPassword(String password) {
  811.                 this.password = password;
  812.         }
  813.  
  814.         public String getUserName() {
  815.                 return userName;
  816.         }
  817.  
  818.         public void setUserName(String userName) {
  819.                 this.userName = userName;
  820.         }
  821. }
  822.  

回复 "java邮件接收器 pop3协议"

这儿你可以回复上面这条便签

captcha