Import Lombok.extern.slf4j.slf4j;import Org.springframework.beans.factory.annotation.value;import javax.mail.*; Import Javax.mail.internet.internetaddress;import Javax.mail.internet.mimemessage;import Javax.mail.internet.mimemultipart;import Javax.mail.internet.mimeutility;import Java.io.*;import Java.text.simpledateformat;import java.util.date;import java.util.properties;/** * Resolve mail Help class using POP3 protocol * * @author Bzs on 2018/6/28. */@Slf4jpublic class Parsingemailutil {public static void main (string[] args) throws exception{resceive ("* * * * @163.com "," * * * * * "); /** * Get mailbox information * * @param emailadress Email Address required to resolve * @param password Email authorization password * @throws Exception */public static void Resceive (string emailadress, String password) throws Exception {string port = "110"; Port number String ServicePath = "pop.163.com"; Server address//Prepare session information for the connection server properties props = new properties (); Props.setproperty ("Mail.store.protocol", "POP3 "); Use the POP3 protocol Props.setproperty ("Mail.pop3.port", port); Port Props.setproperty ("Mail.pop3.host", ServicePath); POP3 server//Create Session instance object Session session = Session.getinstance (props); Store store = Session.getstore ("POP3"); Store.connect (emailadress, password); 163 Mailbox Program Login is a third-party login so the password here is 163 give the authorization password instead of the normal login password//Get Inbox folder folder = Store.getfolder ("INBOX"); /* Folder.read_only: Read-only permission * Folder.read_write: Readable and writable (can modify the status of the message) */Folder.open (folder.read_write); Open Inbox////Because the POP3 protocol is unable to learn the status of the message, Getunreadmessagecount gets the total number of messages in the Inbox//System.out.println ("Unread messages:" + FOLDER.G Etunreadmessagecount ());//////Because the POP3 protocol is unable to know the status of the message, the following results are always 0//System.out.println ("Deleted messages:" + folder.ge Tdeletedmessagecount ());//System.out.println ("New mail:" + folder.getnewmessagecount ()); Get the total number of messages in your Inbox Log.warn ("Total number of messages: {}", Folder.getmessagecount ()); Get in InboxAll messages, and parse message[] messages = Folder.getmessages (); Parse message parsemessage (messages); Get all the messages in your Inbox and delete messages//deleteMessage (messages); Frees resource Folder.close (TRUE); Store.close (); /** * Parse Message * * @param messages List of messages to resolve */public static void Parsemessage (Message ... messages) th Rows Messagingexception, IOException {if (messages = = NULL | | Messages.length < 1) throw new Messagi Ngexception ("No messages found to resolve!"); Resolve all messages for (int i = 0, count = messages.length; i < count; i++) {mimemessage msg = (mimemessage) Messages[i]; Log.info ("------------------parse" + msg.getmessagenumber () + "email--------------------"); Log.warn ("Subject: {}", Getsubject (msg)); Log.warn ("Sender: {}", Getfrom (msg)); Log.warn ("Recipient: {}", getreceiveaddress (msg, null)); Log.warn ("Send time: {}", getsentdate (msg, null)); Log.warn ("read: {}", Isseen (MSG)); Log.warn ("message priority: {}", GetPriority (msg)); Log.warn ("Whether a receipt is required: {}", Isreplysign (msg)); Log.warn ("message size: {}", msg.getsize () * 1024x768 + "KB"); Boolean iscontainerattachment = Iscontainattachment (msg); Log.warn ("Whether it contains attachments: {}", iscontainerattachment); if (iscontainerattachment) {saveattachment (msg, "d:\\log\\" + msg.getsubject () + "_" + i + "_");//Save Attachments } stringbuffer content = new StringBuffer (30); Parse message body getmailtextcontent (msg, content); Log.warn ("message body: {}", content); Log.info ("------------------" + msg.getmessagenumber () + "End of email parsing--------------------"); System.out.println (); }}/** * Delete message * * @param messages to delete a mailing list */public static void DeleteMessage (Message ... message s) throws Messagingexception, IOException {if (messages = = NULL | | Messages.length < 1) throw new Me SsagingeXception ("No messages found to resolve!"); Resolve all messages for (int i = 0, count = messages.length; i < count; i++) {/** * mail delete */Message message = Messages[i]; String subject = Message.getsubject (); Set the DELETE flag to True Message.setflag (Flags.Flag.DELETED, true); System.out.println ("Marked DELETE for message:" + subject); }}/** * Get message subject * * @param msg Message contents * @return Decoded message subject */public static String Getsubject (Mi Memessage msg) throws Unsupportedencodingexception, Messagingexception {return Mimeutility.decodetext (msg.getSubje CT ()); /** * Get Mail Sender * * @param msg Message contents * @return Name <email address > * @throws messagingexception * @throws unsupportedencodingexception */public static String Getfrom (MimeMessage msg) throws Messagingexception, U nsupportedencodingexception {String from = ""; Address[] FrOMS = Msg.getfrom (); if (Froms.length < 1) throw new Messagingexception ("No sender!"); InternetAddress address = (internetaddress) froms[0]; String person = address.getpersonal (); if (person! = null) {person = Mimeutility.decodetext (person) + ""; } else {person = ""; } from = person + "<" + address.getaddress () + ">"; return from; /** * Get mail, CC, and Bcc addresses based on recipient type. If the recipient type is empty, get all recipients * <p>message.recipienttype.to recipients </p> * <p>message.recipienttype.cc cc < /p> * <P>MESSAGE.RECIPIENTTYPE.BCC </p> * * @param msg message content * @param type recipient type * @r Eturn Recipient 1 < e-mail address 1>, Recipient 2 < email address 2>, ... * @throws messagingexception */public static String Getrecei Veaddress (mimemessage msg, Message.recipienttype type) throws Messagingexception {StringBuffer receiveaddress = NE W StringBuffer (); Address[] AddreSSS = NULL; if (type = = null) {addresss = Msg.getallrecipients (); } else {addresss = msg.getrecipients (type); } if (addresss = = NULL | | Addresss.length < 1) throw new Messagingexception ("No recipient!"); for (address address:addresss) {internetaddress internetaddress = (internetaddress) Address; Receiveaddress.append (Internetaddress.tounicodestring ()). Append (","); } Receiveaddress.deletecharat (Receiveaddress.length ()-1); Delete the last comma return receiveaddress.tostring (); /** * Get mail delivery time * * @param msg message content * @return yyyy mm MONTH DD Day week x hh:mm * @throws messagingexception */public static string Getsentdate (MimeMessage msg, string pattern) throws Messagingexception {Date receive Ddate = Msg.getsentdate (); if (receiveddate = = null) return ""; if (pattern = = NULL | | ". Equals (pattern)) pattern =" yyyy mm month DD Day E Hh:mm "; return new SimpleDateFormat (pattern). Format (receiveddate); /** * Determine if the message contains an attachment * * @param part message contents * @return Message exists attachment returns TRUE, there is no return false * @throws Messagingexce ption * @throws IOException */public static Boolean Iscontainattachment (part part) throws Messagingexception, IOException {Boolean flag = false; if (Part.ismimetype ("multipart/*")) {Mimemultipart multipart = (Mimemultipart) part.getcontent (); int partcount = Multipart.getcount (); for (int i = 0; i < Partcount; i++) {BodyPart bodypart = Multipart.getbodypart (i); String disp = bodypart.getdisposition (); if (disp! = null && (disp.equalsignorecase (part.attachment) | | disp.equalsignorecase (part.inline))) { Flag = true; } else if (Bodypart.ismimetype ("multipart/*")) {flag = Iscontainattachment (bodypart); } else { String ContentType = Bodypart.getcontenttype (); if (Contenttype.indexof ("Application")! =-1) {flag = true; } if (Contenttype.indexof ("name")! =-1) {flag = true; }} if (flag) break; }} else if (Part.ismimetype ("message/rfc822")) {flag = Iscontainattachment ((part) part.getcontent ()); } return flag; /** * To determine if the message has been read * * @param msg Message contents * @return return FALSE if the message is read back to True * @throws messagingexception */public static Boolean Isseen (MimeMessage msg) throws Messagingexception {return msg.getflags (). Contains (Flags.Flag.SEEN); /** * Determine if the message requires a read receipt * * @param msg Message contents * @return Need receipts return true, otherwise return false * @throws Messagingexcepti On */public static Boolean isreplysign (MimeMessage msg) throws Messagingexception {Boolean replysign = false; string[] headers = Msg.getheader ("disposition-notification-to"); if (headers! = null) Replysign = true; return replysign; /** * GET Priority message * * @param msg content * @return 1 (High): Emergency 3: Normal (normal) 5: lo (Low) * @throws Messagi Ngexception */public static String getpriority (MimeMessage msg) throws Messagingexception {string priority = "normal"; string[] headers = Msg.getheader ("x-priority"); if (headers! = null) {String headerpriority = headers[0]; if (Headerpriority.indexof ("1")! =-1 | | headerpriority.indexof ("high")! =-1) Priority = "emergency"; else if (Headerpriority.indexof ("5")! =-1 | | headerpriority.indexof ("low")! =-1) Priority = "lower"; else priority = "normal"; } return priority; /** * Get Message text content * * @param part message body * @param content A string that stores the contents of the message text * @throws messagingexception * @throws IOException */public static void Getmailtextcontent (part part, Strin Gbuffer content) throws Messagingexception, IOException {//If it is a text type of attachment, through the GetContent method can be taken to the text content, but this is not the result we need, so here to make a judgment Boolean Iscontaintextattach = Part.getcontenttype (). IndexOf ("name") > 0; if (Part.ismimetype ("text/*") &&!iscontaintextattach) {content.append (Part.getcontent (). toString ()); } else if (Part.ismimetype ("message/rfc822")) {Getmailtextcontent ((part) part.getcontent (), content); } else if (Part.ismimetype ("multipart/*")) {multipart multipart = (multipart) part.getcontent (); int partcount = Multipart.getcount (); for (int i = 0; i < Partcount; i++) {BodyPart bodypart = Multipart.getbodypart (i); Getmailtextcontent (bodypart, content); }}}/** * Save attachments * * @param one of several compositions in a part message * @param destDir Attachment Save directory * @throws unsupportedencodingexception * @throws messagingexception * @throws File Notfoundexception * @throws IOException */public static void Saveattachment (part part, String DestDir) throws Messagingexception, IOException {if (Part.ismimetype ("multipart/*")) {multipart multipart = (multipart ) part.getcontent (); Complex message//complex message contains multiple message body int partcount = Multipart.getcount (); for (int i = 0; i < Partcount; i++) {//Get one of the message body in complex message bodypart BodyPart = Multipart.get BodyPart (i); A message body may also be a complex body of multiple mail bodies, String disp = bodypart.getdisposition (); if (disp! = null && (disp.equalsignorecase (part.attachment) | | disp.equalsignorecase (part.inline))) { InputStream is = Bodypart.getinputstream (); SaveFile (IS, DestDir, Decodetext (Bodypart.getfilename ())); } ELSE if (Bodypart.ismimetype ("multipart/*")) {saveattachment (bodypart, DestDir); } else {String contentType = Bodypart.getcontenttype (); if (Contenttype.indexof ("name")! =-1 | | contenttype.indexof ("application")! =-1) {SaveFile (bodyp Art.getinputstream (), DestDir, Decodetext (Bodypart.getfilename ())); }}}} and Else if (Part.ismimetype ("message/rfc822")) {Saveattachment ((part) PA Rt.getcontent (), DestDir); }}/** * Data from the input stream is saved to the specified directory * * @param is input stream * @param filename filename * @param destDir file storage Record * @throws FileNotFoundException * @throws IOException */private static void SaveFile (InputStream is, Str ing DestDir, String fileName) throws FileNotFoundException, IOException {Bufferedinputstream bis = new BUFFEREDINP Utstream (IS); Bufferedoutputstream BOS = new BuffereDoutputstream (New FileOutputStream (New File (DestDir + fileName)); int len =-1; while (len = Bis.read ())! =-1) {bos.write (len); Bos.flush (); } bos.close (); Bis.close (); }/** * Text decoding * * @param encodetext decoding mimeutility.encodetext (String text) method encoded text * @return Decoded text * @throws unsupportedencodingexception */public static string Decodetext (String encodetext) throws Unsupportedencod ingexception {if (Encodetext = = NULL | | ". Equals (Encodetext)) {return" "; } else {return mimeutility.decodetext (encodetext); } }}
This method allows you to resolve the details of a message in a mailbox.
Java resolves message information in a mailbox