首页 > 代码库 > JavaMail入门第五篇 解析邮件

JavaMail入门第五篇 解析邮件

上一篇JavaMail入门第四篇 接收邮件中,控制台打印出的内容,我们无法阅读,其实,让我们自己来解析一封复杂的邮件是很不容易的,邮件里面格式、规范复杂得很。不过,我们所用的浏览器内置了解析各种数据类型的数据处理模块,我们只需要在把数据流传输给浏览器之前明确地指定该数据流属于哪种数据类型即可,之后一切的解析操作由浏览器自动帮我们完成。下面这张图可以很好的说明解析邮件的步骤

技术分享

1、调用Message对象的getFrom、getSubject等方法,可以得到邮件的发件人和主题等信息,调用getContentType方法得到邮件的类型;

2、通过Message.getContentType方法的返回值判断邮件类型,并调用Message.getContent方法得到邮件内容。如果邮件类型为"text/plain"或者"text/html",表示邮件内容为纯文本,此时调用Message对象的getContent方法得到邮件内容,然后将返回对象的类型转换成String输出给显示软件即可。如果邮件类型为"multipart/*",表示邮件内容是一个复合类型,此时需将Message.getContent方法复合的对象转换成Multipart。

3、调用Multipart对象的getCount方法检测Multipart对象中封装了多少个BodyPart对象,并通过for循环逐一取出Multipart对象中的每个BodyPart对象进行处理。

4、在处理每个BodyPart对象时,首先调用BodyPart对象的getContentType方法得到它的MIME类型,然后根据MIME类型作出如下三种情况的处理:

  当MIME类型为"text/*"时,表示BodyPart对象中保存的是纯文本数据,如上图中的"text/plain",此时第一BodyPart对象的getContent方法并将返回的对象转换成String输出给显示软件显示即可。

  当MIME类型表示的是图片、声音或者是附件等二进制数据时,如上图中的"image/gif"时,此时应调用BodyPart对象的getDataHandler方法得到了封装了数据的DataHanlder对象,然后调用DataHandler对象的getInputStream方法获得与数据相关联的InputStream对象,通过这个InputStream对象中即可获得原始的二进制数据内容。

  当MIME类型为"multipart/mixed"时,表示BodyPart对象中保存的是一个复合MIME消息,此时应调用BodyPart对象的getContent方法得到封装复合MIME消息的对象并将它转换成Multipart类型,接着重复第3和第4个步骤操作对Multipart对象进行递归调用。

下面来编写一个接收并解析带有附件的程序

POP3Help.java

 1 package mail;
 2 
 3 import java.util.Properties;
 4 
 5 import javax.mail.Folder;
 6 import javax.mail.Session;
 7 import javax.mail.Store;
 8 
 9 public class POP3Help {
10     public static Folder getFolder(String host, String username, String password) {
11         Properties prop = new Properties();
12         prop.setProperty("mail.store.protocol", "pop3");
13         prop.setProperty("mail.pop3.host", host);
14 
15         Session mailSession = Session.getDefaultInstance(prop, null);
16         mailSession.setDebug(false);
17 
18         try {
19             Store store = mailSession.getStore("pop3");
20             store.connect(host, username, password);
21             Folder folder = store.getFolder("inbox");
22             folder.open(Folder.READ_WRITE);
23             return folder;
24         } catch (Exception e) {
25             e.printStackTrace();
26         }
27 
28         return null;
29     }
30 }

该类用来连接和登录POP3服务器,并返回代表邮件夹的Folder对象

 

index.html

 1 <html>
 2   <head>
 3     <title>login.html</title>
 4   </head>
 5   <body>
 6     <form action="login.jsp" method="post">
 7         主机名:<input name="host" type="text"><br/>
 8         用户名:<input name="username" type="text"><br/>
 9         密码:<input name="password" type="password"><br/>
10         <input type="submit" value="提交"> 
11         <input type="reset" value="重置">
12     </form>
13   </body>
14 </html>

登录页面,需要用户填写邮件服务器的主机名,用户名和密码

 

login.jsp

 1 <%@ page import="javax.mail.*,mail.*"
 2  contentType="text/html;charset=GB2312" %>
 3 <%
 4     String host = request.getParameter("host");      
 5       String username = request.getParameter("username");
 6       String password = request.getParameter("password");
 7       String from = "";
 8       String subject = "";    
 9       Folder folder = POP3Help.getFolder(host,username,password);
10       session.setAttribute("folder",folder);
11       Message [] messages = folder.getMessages();
12       
13       for(int i=0;i<messages.length;i++)
14       {
15           try
16           {
17               from = messages[i].getFrom()[0].toString();
18             subject = messages[i].getSubject();
19             out.print(i + 1);
20 %>
21             发件人地址:<%=from %>  邮件主题:<%=subject %>                
22             <a href="displayMsg.jsp?msgnum=<%=i+1%>">查看邮件</a><br/>
23 <%
24         }
25             catch(Exception e){}
26           }
27 %>

获取邮件夹中的所有邮件

 

displayMsg.jsp

1 <frameset rows="25%,*">
2     <frame src="/mailDemo/DisplayHead?msgnum=<%=request.getParameter("msgnum")%>" scrolling="no">
3     <frame src="/mailDemo/DisplayContent?msgnum=<%=request.getParameter("msgnum")%>" scrolling="no">
4 </frameset>

用于展示邮件的信息

 

DisplayHead.java

 1 package mail;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.text.DateFormat;
 6 
 7 import javax.mail.BodyPart;
 8 import javax.mail.Folder;
 9 import javax.mail.Message;
10 import javax.mail.Multipart;
11 import javax.mail.internet.MimeUtility;
12 import javax.servlet.ServletException;
13 import javax.servlet.http.HttpServlet;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import javax.servlet.http.HttpSession;
17 
18 @SuppressWarnings("serial")
19 public class DisplayHead extends HttpServlet {
20     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
21         response.setContentType("text/html;charset=gb2312");
22         PrintWriter out = response.getWriter();
23         HttpSession session = request.getSession();
24         int msgnum = Integer.parseInt(request.getParameter("msgnum"));
25         Folder folder = (Folder) session.getAttribute("folder");
26 
27         try {
28             Message msg = folder.getMessage(msgnum);
29             String from = msg.getFrom()[0].toString();
30             String subject = msg.getSubject();
31             String sendDate = DateFormat.getInstance().format(msg.getSentDate());
32 
33             out.println("邮件主题:" + subject + "<br/>");
34             out.println("发件人:" + from + "<br/>");
35             out.println("发送日期:" + sendDate + "<br/><br/>");
36 
37             System.out.println("contentType:" + msg.getContentType());
38 
39             // 如果该邮件是组合型"multipart/*"则可能包含附件等
40             if (msg.isMimeType("multipart/*")) {
41                 Multipart mp = (Multipart) msg.getContent();
42 
43                 for (int i = 0; i < mp.getCount(); i++) {
44                     BodyPart bp = mp.getBodyPart(i);
45 
46                     // 如果该BodyPart对象包含附件,则应该解析出来
47                     if (bp.getDisposition() != null) {
48                         String filename = bp.getFileName();
49                         System.out.println("filename:" + filename);
50                         
51                         if (filename.startsWith("=?")) {
52                             // 把文件名编码成符合RFC822规范
53                             filename = MimeUtility.decodeText(filename);
54                         }
55 
56                         // 生成打开附件的超链接
57                         out.print("附件:");
58                         out.print("<a href=http://www.mamicode.com/HandleAttach?msgnum=" + msgnum + "&&bodynum=" + i + "&&filename=" + filename
59                                 + ">" + filename + "</a><br/>");
60                     }
61                 }
62             }
63         } catch (Exception e) {
64             e.printStackTrace();
65         }
66     }
67 }

用于显示邮件头内容

 

DisplayContent.java

 1 package mail;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.mail.BodyPart;
 6 import javax.mail.Folder;
 7 import javax.mail.Message;
 8 import javax.mail.Multipart;
 9 import javax.servlet.ServletException;
10 import javax.servlet.ServletOutputStream;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 import javax.servlet.http.HttpSession;
15 
16 @SuppressWarnings("serial")
17 public class DisplayContent extends HttpServlet {
18     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         ServletOutputStream sos = response.getOutputStream();
20         HttpSession session = request.getSession();
21         int msgnum = Integer.parseInt(request.getParameter("msgnum"));
22         Folder folder = (Folder) session.getAttribute("folder");
23 
24         try {
25             Message msg = folder.getMessage(msgnum);
26             // 邮件类型不是mixed时,表示邮件中不包含附件,直接输出邮件内容
27             if (!msg.isMimeType("multipart/mixed")) {
28                 response.setContentType("message/rfc822");
29                 msg.writeTo(sos);
30             } else {
31                 // 查找并输出邮件中的邮件正文
32                 Multipart mp = (Multipart) msg.getContent();
33                 int bodynum = mp.getCount();
34                 for (int i = 0; i < bodynum; i++) {
35                     BodyPart bp = mp.getBodyPart(i);
36                     /*
37                      * MIME消息头中不包含disposition字段, 并且MIME消息类型不为mixed时,
38                      * 表示当前获得的MIME消息为邮件正文
39                      */
40                     if (!bp.isMimeType("multipart/mixed") && bp.getDisposition() == null) {
41                         response.setContentType("message/rfc822");
42                         bp.writeTo(sos);
43                     }
44                 }
45             }
46         } catch (Exception e) {
47             e.printStackTrace();
48         }
49     }
50 }

用于显示邮件正文

 

HandleAttact.java

 1 package mail;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import javax.mail.BodyPart;
 6 import javax.mail.Folder;
 7 import javax.mail.Message;
 8 import javax.mail.Multipart;
 9 import javax.servlet.ServletException;
10 import javax.servlet.ServletOutputStream;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 import javax.servlet.http.HttpSession;
15 
16 @SuppressWarnings("serial")
17 public class HandleAttach extends HttpServlet {
18     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         response.setContentType("text/html");
20         HttpSession session = request.getSession();
21         ServletOutputStream out = response.getOutputStream();
22 
23         int msgnum = Integer.parseInt(request.getParameter("msgnum"));
24         int bodynum = Integer.parseInt(request.getParameter("bodynum"));
25         String filename = request.getParameter("filename");
26         Folder folder = (Folder) session.getAttribute("folder");
27 
28         try {
29             Message msg = folder.getMessage(msgnum);
30 
31             // 将消息头类型设置为附件类型
32             response.setHeader("Content-Disposition", "attachment;filename=" + filename);
33             
34             Multipart multi = (Multipart) msg.getContent();
35             BodyPart bodyPart = multi.getBodyPart(bodynum);
36             
37             InputStream is = bodyPart.getInputStream();
38             int c = 0;
39             while ((c = is.read()) != -1) {
40                 out.write(c);
41             }
42         } catch (Exception e) {
43             e.printStackTrace();
44         }
45     }
46 }

用于处理附件

 

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 3       <display-name>mailDemo</display-name>
 4       <welcome-file-list>
 5         <welcome-file>index.html</welcome-file>
 6         <welcome-file>index.htm</welcome-file>
 7         <welcome-file>index.jsp</welcome-file>
 8         <welcome-file>default.html</welcome-file>
 9         <welcome-file>default.htm</welcome-file>
10         <welcome-file>default.jsp</welcome-file>
11       </welcome-file-list>
12   
13       <servlet> 
14         <servlet-name>DisplayHead</servlet-name> 
15         <servlet-class>mail.DisplayHead</servlet-class> 
16     </servlet>      
17     <servlet-mapping> 
18         <servlet-name>DisplayHead</servlet-name> 
19         <url-pattern>/DisplayHead</url-pattern> 
20     </servlet-mapping> 
21        
22     <servlet> 
23         <servlet-name>DisplayContent</servlet-name> 
24         <servlet-class>mail.DisplayContent</servlet-class> 
25     </servlet>      
26     <servlet-mapping> 
27         <servlet-name>DisplayContent</servlet-name> 
28         <url-pattern>/DisplayContent</url-pattern> 
29     </servlet-mapping>      
30        
31     <servlet> 
32         <servlet-name>HandleAttach</servlet-name> 
33         <servlet-class>mail.HandleAttach</servlet-class> 
34     </servlet>      
35     <servlet-mapping> 
36         <servlet-name>HandleAttach</servlet-name> 
37         <url-pattern>/HandleAttach</url-pattern> 
38     </servlet-mapping> 
39 </web-app>

 

 

首先启动tomcat服务器,然后在浏览器中输入http://localhost:8080/mailDemo/index.html

技术分享

输入用户名跟密码(这里需要填写授权码,什么是授权码,它又是如何设置?

技术分享

列出了邮件夹中所有的邮件

 

点击查看邮件链接

技术分享

点击附件后面的文件名称即可下载对应附件。

JavaMail入门第五篇 解析邮件