Previous articleIntroduction to JavaMail, the fourth article in receiving emails, we cannot read the content printed on the console. In fact, it is not easy to let us analyze a complex email by ourselves. The format and specifications in the email are very complicated. However, the browser we use is built-in data processing module for analyzing various data types. We only need to clearly specify which data type the data stream belongs to before transmitting the data stream to the browser. After that, all the parsing operations will be automatically completed by the browser. The following picture can explain the steps to parse emails well
1. Call the getFrom, getSubject and other methods of the Message object to get the sender and subject of the email, and call the getContentType method to get the type of the email;
2. Use the return value of the Message.getContentType method to determine the email type, and call the Message.getContent method to obtain the email content. If the email type is "text/plain" or "text/html", it means that the email content is plain text. At this time, call the getContent method of the Message object to get the email content, and then convert the type of the returned object into a String and output it to the display software. If the message type is "multipart/*", it means that the message content is a compound type. At this time, the object compounded by the Message.getContent method needs to be converted into Multipart.
3. Call the getCount method of the Multipart object to detect how many BodyPart objects are encapsulated in the Multipart object, and take out each BodyPart object in the Multipart object one by one through a for loop for processing.
4. When processing each BodyPart object, first call the getContentType method of the BodyPart object to get its MIME type, and then handle the following three situations based on the MIME type:
When the MIME type is "text/*", it means that the BodyPart object is stored in plain text data, as shown in the above figure. At this time, the getContent method of the first BodyPart object and convert the returned object into a String and output it to the display software for display.
When the MIME type represents binary data such as pictures, sounds, or attachments, as in the "image/gif" in the figure above, the getDataHandler method of the BodyPart object should be called to obtain the DataHanlder object encapsulated by the data, and then the getInputStream method of the DataHandler object is called to obtain the InputStream object associated with the data. The original binary data content can be obtained through this InputStream object.
When the MIME type is "multipart/mixed", it means that the BodyPart object is stored in the compound MIME message. At this time, the getContent method of the BodyPart object should be called to obtain the object that encapsulates the compound MIME message and converts it to the Multipart type. Then repeat the 3rd and 4th steps to make recursive calls to the Multipart object.
Let's write a program that receives and parses the attachments
POP3Help.java
package mail;import java.util.Properties;import javax.mail.Folder;import javax.mail.Session;import javax.mail.Store;public class POP3Help { public static Folder getFolder(String host, String username, String password) { Properties prop = new Properties(); prop.setProperty("mail.store.protocol", "pop3"); prop.setProperty("mail.pop3.host", host); Session mailSession = Session.getDefaultInstance(prop, null); mailSession.setDebug(false); try { Store store = mailSession.getStore("pop3"); store.connect(host, username, password); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_WRITE); return folder; } catch (Exception e) { e.printStackTrace(); } return null; }}This class is used to connect and log in to the POP3 server and return the Folder object representing the mail folder
index.html
<html> <head> <title>login.html</title> </head> <body> <form action="login.jsp" method="post"> Host name: <input name="host" type="text"><br/> Username:<input name="username" type="text"><br/> Password:<input name="password"><br/> <input type="submit" value="submit"> <input type="reset" value="reset"> </form> </body></html>
Login page, the user needs to fill in the host name, user name and password of the mail server
login.jsp
<%@ page import="javax.mail.*,mail.*" contentType="text/html;charset=GB2312" %><% String host = request.getParameter("host"); String username = request.getParameter("username"); String password = request.getParameter("password"); String from = ""; String subject = ""; Folder folder = POP3Help.getFolder(host,username,password); session.setAttribute("folder",folder); Message [] messages = folder.getMessages(); for(int i=0;i<messages.length;i++) { try { from = messages[i].getFrom()[0].toString(); subject = messages[i].getSubject(); out.print(i + 1);%> Sender address: <%=from %> Email subject: <%=subject %> <a href="displayMsg.jsp?msgnum=<%=i+1%>">View email</a><br/><% } catch(Exception e){} }%>Get all messages in the mail folder
displayMsg.jsp
<frameset rows="25%,*"> <frame src="/mailDemo/DisplayHead?msgnum=<%=request.getParameter("msgnum")%>" scrolling="no"> <frame src="/mailDemo/DisplayContent?msgnum=<%=request.getParameter("msgnum")%>" scrolling="no"></frameset>Information used to display emails
DisplayHead.java
package mail;import java.io.IOException;import java.io.PrintWriter;import java.text.DateFormat;import javax.mail.BodyPart;import javax.mail.Folder;import javax.mail.Message;import javax.mail.Multipart;import javax.mail.internet.MimeUtility;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@SuppressWarnings("serial")public class DisplayHead extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); int msgnum = Integer.parseInt(request.getParameter("msgnum")); Folder folder = (Folder) session.getAttribute("folder"); try { Message msg = folder.getMessage(msgnum); String from = msg.getFrom()[0].toString(); String subject = msg.getSubject(); String sendDate = DateFormat.getInstance().format(msg.getSentDate()); out.println("Mail subject: " + subject + "<br/>"); out.println("Sender:" + from + "<br/>"); out.println("Send date: " + sendDate + "<br/><br/>"); System.out.println("contentType:" + msg.getContentType()); // If the message is a combination "multipart/*", it may contain attachments, etc. (msg.isMimeType("multipart/*")) { Multipart mp = (Multipart) msg.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); // If the BodyPart object contains attachments, it should be parsed if (bp.getDisposition() != null) { String filename = bp.getFileName(); System.out.println("filename:" + filename); if (filename.startsWith("=?")) { // Encode the file name to comply with the RFC822 specification filename = MimeUtility.decodeText(filename); } // Generate a hyperlink to open the attachment out.print("Attach:"); out.print("<a href=HandleAttach?msgnum=" + msgnum + "&&bodynum=" + i + "&&filename=" + filename + ">" + filename + "</a><br/>"); } } } } catch (Exception e) { e.printStackTrace(); } }}Used to display the content of the email header
DisplayContent.java
package mail;import java.io.IOException;import javax.mail.BodyPart;import javax.mail.Folder;import javax.mail.Message;import javax.mail.Multipart;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@SuppressWarnings("serial")public class DisplayContent extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream sos = response.getOutputStream(); HttpSession session = request.getSession(); int msgnum = Integer.parseInt(request.getParameter("msgnum")); Folder folder = (Folder) session.getAttribute("folder"); try { Message msg = folder.getMessage(msgnum); // When the message type is not mixed, it means that the message does not contain attachments, and the message content is directly output if (!msg.isMimeType("multipart/mixed")) { response.setContentType("message/rfc822"); msg.writeTo(sos); } else { // Find and output the email body in the email Multipart mp = (Multipart) msg.getContent(); int bodynum = mp.getCount(); for (int i = 0; i < bodynum; i++) { BodyPart bp = mp.getBodyPart(i); /* * When the MIME message header does not contain the disposition field, and the MIME message type is not mixed, * indicates that the currently obtained MIME message is the email body*/ if (!bp.isMimeType("multipart/mixed") && bp.getDisposition() == null) { response.setContentType("message/rfc822"); bp.writeTo(sos); } } } } catch (Exception e) { e.printStackTrace(); } }}Used to display the email body
HandleAttact.java
package mail;import java.io.IOException;import java.io.InputStream;import javax.mail.BodyPart;import javax.mail.Folder;import javax.mail.Message;import javax.mail.Multipart;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@SuppressWarnings("serial")public class HandleAttach extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); ServletOutputStream out = response.getOutputStream(); int msgnum = Integer.parseInt(request.getParameter("msgnum")); int bodynum = Integer.parseInt(request.getParameter("bodynum")); String filename = request.getParameter("filename"); Folder folder = (Folder) session.getAttribute("folder"); try { Message msg = folder.getMessage(msgnum); // Set the message header type to attachment type response.setHeader("Content-Disposition", "attachment;filename=" + filename); Multipart multi = (Multipart) msg.getContent(); BodyPart bodyPart = multi.getBodyPart(bodynum); InputStream is = bodyPart.getInputStream(); int c = 0; while ((c = is.read()) != -1) { out.write(c); } } catch (Exception e) { e.printStackTrace(); } }}Used to handle attachments
web.xml
<?xml version="1.0" encoding="UTF-8"?><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" 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"> <display-name>mailDemo</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>DisplayHead</servlet-name> <servlet-class>mail.DisplayHead</servlet-class> </servlet> <servlet-mapping> <servlet-name>DisplayHead</servlet-name> <url-pattern>/DisplayHead</url-pattern> </servlet-mapping> <servlet> <servlet-name>DisplayContent</servlet-name> <servlet-class>mail.DisplayContent</servlet-class> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name>DisplayContent</servlet-name> <url-pattern>/DisplayContent</url-pattern> </servlet-mapping> <servlet> <servlet-name>HandleAttach</servlet-name> <servlet-class>mail.HandleAttach</servlet-class> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name>HandleAttach</servlet-name> <url-pattern>/HandleAttach</url-pattern> </servlet-mapping> </web-app>
First start the tomcat server, and then enter http://localhost:8080/mailDemo/index.html in the browser
Enter the user name and password (the authorization code needs to be filled in here. What is the authorization code and how is it set?)
List all messages in the mail folder
Click to view the email link
Click the file name after the attachment to download the corresponding attachment.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.