Javamail Study Notes (4). Use POP3 protocol to receive and parse emails (all)

Source: Internet
Author: User
Tags rfc822
Package Org. yangxin. study. JM; import Java. io. bufferedinputstream; import Java. io. bufferedoutputstream; import Java. io. file; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. io. unsupportedencodingexception; import Java. text. simpledateformat; import Java. util. date; import Java. util. properties; import javax. mail. address; impo RT javax. mail. bodypart; import javax. mail. flags; import javax. mail. folder; import javax. mail. message; import javax. mail. messagingexception; import javax. mail. multipart; import javax. mail. part; import javax. mail. session; import javax. mail. store; import javax. mail. internet. internetaddress; import javax. mail. internet. mimemessage; import javax. mail. internet. mimemultipart; import javax. mail. internet. mimeutility ;/* ** Use POP3 to receive emails */public class pop3receivemailtest {public static void main (string [] ARGs) throws exception {receive ();} /*** receive email */public static void receive () throws exception {// prepare the session information for connecting to the server properties props = new properties (); props. setproperty ("mail. store. protocol "," POP3 "); // protocol props. setproperty ("mail. pop3.port "," 110 "); // port props. setproperty ("mail. pop3.host "," pop3.163.com "); // POP3 server // create Create session instance object session = session. getinstance (props); store = session. getstore ("POP3"); store. connect ("xyang0917@163.com", "123456abc"); // get inbox folder = store. getfolder ("inbox");/* folder. read_only: Read-Only permission * folder. read_write: readable and writable (you can modify the mail status) */folder. open (folder. read_write); // open the inbox // because the POP3 Protocol cannot know the mail status, getunreadmessagecount returns the total number of emails in the inbox system. out. println ("Number of unread mails:" + folder. getunreadmes Sagecount (); // because the POP3 Protocol cannot know the mail status, the following results are always 0 system. out. println ("Number of deleted mails:" + folder. getdeletedmessagecount (); system. out. println ("New Mail:" + folder. getnewmessagecount (); // get the total number of emails in the inbox system. out. println ("Total number of Emails:" + folder. getmessagecount (); // get all emails in the inbox and parse the message [] messages = folder. getmessages (); parsemessage (messages); // release the resource folder. close (true); store. close ();}/*** resolve email * @ Param messages the email column to be parsed Table */public static void parsemessage (message... messages) throws messagingexception, ioexception {If (messages = NULL | messages. length <1) throw new messagingexception ("the email to be parsed is not found! "); // Parse all emails for (INT I = 0, Count = messages. length; I <count; I ++) {mimemessage MSG = (mimemessage) messages [I]; system. out. println ("------------------ Parsing" + MSG. getmessagenumber () + "email --------------------"); system. out. println ("topic:" + getsubject (MSG); system. out. println ("Sender:" + getfrom (MSG); system. out. println ("Recipient:" + getreceiveaddress (MSG, null); system. out. println ("sent at:" + getsentdate (MS G, null); system. out. println ("read:" + isseen (MSG); system. out. println ("mail priority:" + getpriority (MSG); system. out. println ("whether receipt is required:" + isreplysign (MSG); system. out. println ("mail size:" + MSG. getsize () * 1024 + "kb"); Boolean iscontainerattachment = iscontainattachment (MSG); system. out. println ("include attachment:" + iscontainerattachment); If (iscontainerattachment) {saveattachment (MSG, "C: \ mailtmp \" + MSG. getsubject () + "_"); // Save the attachment} stringbuffer content = new stringbuffer (30); getmailtextcontent (MSG, content); system. out. println ("mail body:" + (content. length ()> 100? Content. substring (0,100) + "... ": Content); system. out. println ("------------------ No." + MSG. getmessagenumber () + "mail resolution ended --------------------"); system. out. println () ;}}/*** get email subject * @ Param MSG email content * @ return decoded Email Subject */public static string getsubject (mimemessage MSG) throws unsupportedencodingexception, messagingexception {return mimeutility. decodetext (MSG. getsubject ();}/*** get the mail sender * @ Param MS G mail content * @ return name <email address> * @ throws messagingexception * @ throws unsupportedencodingexception */public static string getfrom (mimemessage MSG) throws messagingexception, unsupportedencodingexception {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;}/*** obtains the mail recipient, CC, and BCC addresses based on the recipient type. If the recipient type is null, all recipients are obtained * <p> message. recipienttype. to recipient </P> * <p> message. recipienttype. CC </P> * <p> message. recipienttype. BCC </P> * @ Param MSG email content * @ Param type recipient type * @ return recipient 1 <email address 1>, recipient 2 <email address 2> ,... * @ throws messagingexception */public static string getreceiveaddress (mimemessage MSG, message. recipienttype type) throws messagingexception {stringbuffer receiveaddress = new 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: addresss) {internetaddress = (internetaddress) address; receiveaddress. append (internetaddress. tounicodestring ()). append (",");} receiveaddress. deletecharat (receiveaddress. length ()-1); // Delete the last comma return receiveaddress. tostring ();}/*** get mail sending time * @ Param MSG mail content * @ return yyyy mm dd Day Week x hh: mm * @ throws messagingexception */public static string getsentdate (mimemes Sage MSG, string pattern) throws messagingexception {date receiveddate = MSG. getsentdate (); If (receiveddate = NULL) Return ""; if (pattern = NULL | "". equals (pattern) pattern = "YYYY mm dd e hh: mm"; return New simpledateformat (pattern ). format (receiveddate);}/*** determines whether an email contains an attachment * @ Param MSG content * @ return if an attachment exists in the email. True is returned, otherwise, false * @ throws messagingexception * @ throws ioexception */public static Bo is returned. Olean iscontainattachment (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 = 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;}/*** determines whether the email has been read * @ Param MSG content * @ return true if the email has been read, otherwise, false * @ throws messagingexception */public static Boolean isseen (mimemessage MSG) throws messagingexception {return MSG. getflags (). contains (flags. flag. seen);}/*** determines whether the email needs to read the receipt * @ Param MS G mail content * @ return requires a receipt to return true, otherwise false * @ throws messagingexception */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 mail priority * @ Param MSG mail content * @ return 1 (high): urgent 3: normal) 5: low (low) * @ throws messagingexception */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 = "urgent"; else if (headerpriority. indexof ("5 ")! =-1 | headerpriority. indexof ("low ")! =-1) Priority = "low"; elsepriority = "normal";} return priority ;} /*** get the mail text content * @ Param part body * @ Param content the character string storing the mail text content * @ throws messagingexception * @ throws ioexception */public static void getmailtextcontent (Part part, stringbuffer content) throws messagingexception, ioexception {// If an attachment of the text type is used, the text content can be obtained through the getcontent method, but this is not the result we need, so here we need to judge Boolean iscontaintextattach = part. getcontenttype (). indexo F ("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) part. getcontent (); int partcount = multipart. getcount (); For (INT I = 0; I <partcount; I ++) {bodypart = multipart. getbodypart (I); getmailtextcontent (B Odypart, content );}}} /*** Save the attachment ** @ Param Part One of the multiple combinations in the email * @ Param destdir Save the attachment directory * @ throws unsupportedencodingexception * @ throws messagingexception * @ throws filenotfoundexception * @ throws ioexception */public static void saveattachment (Part part, string destdir) throws unsupportedencodingexception, messagingexception, filenotfoundexception, ioexception {If (part. ismimetype ("multipart /*")) {Multipart = (multipart) part. getcontent (); // complex body mail contains multiple body int partcount = multipart. getcount (); For (INT I = 0; I <partcount; I ++) {// obtain one of the complex body emails, bodypart = multipart. getbodypart (I); // a mail body may also be a complex body consisting 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 (bodypart. getinputstream (), destdir, decodetext (bodypart. getfilename () ;}}} else if (part. ismimetype ("message/rfc822") {saveattachment (Part) part. getcontent (), destdir );}} /*** read data from the input stream and save it to the specified directory * @ Param is input stream * @ Param filename file name * @ Param destdir file storage directory * @ throws filenotfoundexception * @ throws ioexception */private static void SaveFile (inputstream is, string destdir, string fil Ename) throws filenotfoundexception, ioexception {bufferedinputstream Bis = new bufferedinputstream (is); bufferedoutputstream Bos = new bytes (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 decode mimeutility. encoded text by the encodetext (string text) Method * @ return decoded text * @ throws unsupportedencodingexception */public static string decodetext (string encodetext) throws unsupportedencodingexception {If (encodetext = NULL | "". equals (encodetext) {return "";} else {return mimeutility. decodetext (encodetext );}}}

Test results:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.