Receive emails from javamail

Source: Internet
Author: User
Tags rfc822
Import Java. io. *; import Java. text. *; import Java. util. *; import javax. mail. *; import javax. mail. internet. *;/*** create a recivemail object when you have an email */public class reciveonemail {private mimemessage = NULL; private string saveattachpath = ""; // The Directory for storing the downloaded attachment: Private stringbuffer bodytext = new stringbuffer (); // Private string dateformat = "YY-mm-dd hh: mm "; // The default display format is public reciveonemail (M Imemessage mimemessage) {This. mimemessage = mimemessage;} public void setmimemessage (mimemessage) {This. mimemessage = mimemessage;}/*** get the sender's address and name */Public String getfrom () throws exception {internetaddress Address [] = (internetaddress []) mimemessage. getfrom (); string from = Address [0]. getaddress (); If (from = NULL) from = ""; string personal = Address [0]. getpersonal (); If (P Ersonal = NULL) Personal = ""; string fromaddr = personal + "<" + from + ">"; return fromaddr;}/*** get the email recipient, CC, and BCC address and name, based on different parameters passed, "to" ---- recipient "cc" --- CC address "BCC" --- BCC address */Public String getmailaddress (string type) throws exception {string mailaddr = ""; string addtype = type. touppercase (); internetaddress [] address = NULL; If (addtype. equals ("to") | addtype. equals ("cc") | addtype. equals ("BCC") {If (addtype. equals ("to") {address = (internetaddress []) mimemessage. getrecipients (message. recipienttype. to);} else if (addtype. equals ("cc") {address = (internetaddress []) mimemessage. getrecipients (message. recipienttype. CC);} else {address = (internetaddress []) mimemessage. getrecipients (message. recipienttype. BCC);} If (address! = NULL) {for (INT I = 0; I <address. length; I ++) {string email = Address [I]. getaddress (); If (email = NULL) email = ""; else {email = mimeutility. decodetext (email);} string personal = Address [I]. getpersonal (); If (Personal = NULL) Personal = ""; else {personal = mimeutility. decodetext (personal);} string compositeto = personal + "<" + email + ">"; mailaddr + = "," + compositeto;} mailaddr = Mailaddr. substring (1) ;}} else {Throw new exception ("error emailaddr type! ");} Return mailaddr;}/*** get email subject */Public String getsubject () throws messagingexception {string subject =" "; try {subject = mimeutility. decodetext (mimemessage. getsubject (); If (subject = NULL) Subject = "";} catch (exception exce) {} return subject ;} /*** get email sending date */Public String getsentdate () throws exception {date sentdate = mimemessage. getsentdate (); simpledateformat format = new Simpledateformat (dateformat); Return format. format (sentdate);}/*** get email body content */Public String getbodytext () {return bodytext. tostring ();}/*** resolve the email and save the obtained email content to a stringbuffer object. The email to be parsed performs different operations based on different mimetype types, step-by-Step parsing */Public void getmailcontent (Part) throws exception {string contenttype = part. getcontenttype (); int nameindex = contenttype. indexof ("name"); Boolean conname = false; If (Nameindex! =-1) conname = true; system. Out. println ("contenttype:" + contenttype); If (part. ismimetype ("text/plain ")&&! Conname) {bodytext. append (string) part. getcontent ();} else if (part. ismimetype ("text/html ")&&! Conname) {bodytext. append (string) part. getcontent ();} else if (part. ismimetype ("multipart/*") {multipart = (multipart) part. getcontent (); int counts = multipart. getcount (); For (INT I = 0; I <counts; I ++) {getmailcontent (multipart. getbodypart (I);} else if (part. ismimetype ("message/rfc822") {getmailcontent (Part) part. getcontent ();} else {}}/*** determines whether a receipt is required for this email. If yes, "true" is returned. ", Otherwise," false "*/Public Boolean getreplysign () throws messagingexception {Boolean replysign = false; string needreply [] = mimemessage. getheader ("disposition-Notification-to"); If (needreply! = NULL) {replysign = true;} return replysign;}/*** get the message-ID */Public String getmessageid () throws messagingexception {return mimemessage. getmessageid ();}/*** [determines whether the email has been read. If the email has not been read, false is returned. Otherwise, true is returned.] */Public Boolean isnew () throws messagingexception {Boolean isnew = false; flags = (Message) mimemessage ). getflags (); flags. flag [] flag = flags. getsystemflags (); system. out. println ("Flags's length:" + flag. length); For (INT I = 0; I <flag. length; I ++) {If (flag [I] = flags. flag. seen) {isnew = true; system. out. println ("seen message ....... "); break;} return isnew;}/*** determines whether the email contains attachments */Public Boolean iscontainattach (Part) throws exception {Boolean attachflag = false; string contenttype = part. getcontenttype (); If (part. ismimetype ("multipart/*") {multipart MP = (Multipart) part. getcontent (); For (INT I = 0; I <MP. getcount (); I ++) {bodypart mpart = MP. getbodypart (I); string disposition = mpart. getdisposition (); If (Disposition! = NULL) & (disposition. equals (part. attachment) | (disposition. equals (part. inline) attachflag = true; else if (mpart. ismimetype ("multipart/*") {attachflag = iscontainattach (Part) mpart);} else {string contype = mpart. getcontenttype (); If (contype. tolowercase (). indexof ("application ")! =-1) attachflag = true; If (contype. tolowercase (). indexof ("name ")! =-1) attachflag = true ;}} else if (part. ismimetype ("message/rfc822") {attachflag = iscontainattach (Part) part. getcontent ();} return attachflag;}/*** [Save attachment] */Public void saveattachment (Part) throws exception {string filename = ""; if (part. ismimetype ("multipart/*") {multipart MP = (multipart) part. getcontent (); For (INT I = 0; I <MP. getcount (); I ++) {bodypart mpart = MP. getb Odypart (I); string disposition = mpart. getdisposition (); If (Disposition! = NULL) & (disposition. equals (part. attachment) | (disposition. equals (part. inline) {filename = mpart. getfilename (); If (filename. tolowercase (). indexof ("gb2312 ")! =-1) {filename = mimeutility. decodetext (filename);} SaveFile (filename, mpart. getinputstream ();} else if (mpart. ismimetype ("multipart/*") {saveattachment (mpart);} else {filename = mpart. getfilename (); If (filename! = NULL) & (filename. tolowercase (). indexof ("gb2312 ")! =-1) {filename = mimeutility. decodetext (filename); SaveFile (filename, mpart. getinputstream () ;}}} else if (part. ismimetype ("message/rfc822") {saveattachment (Part) part. getcontent () ;}}/*** [set the attachment storage path] */Public void setattachpath (string attachpath) {This. saveattachpath = attachpath;}/*** [set date display format] */Public void setdateformat (string format) throws exception {This. dateformat = fo Rmat;}/*** [obtain the attachment storage path] */Public String getattachpath () {return saveattachpath ;} /*** [Save the attachment to the specified directory] */private void SaveFile (string filename, inputstream in) throws exception {string osname = system. getproperty ("OS. name "); string storedir = getattachpath (); string separator =" "; if (osname = NULL) osname =" "; if (osname. tolowercase (). indexof ("win ")! =-1) {separator = "\"; if (storedir = NULL | storedir. equals ("") storedir = "C: \ tmp";} else {separator = "/"; storedir = "/tmp ";} file storefile = new file (storedir + separator + filename); system. out. println ("storefile's path:" + storefile. tostring (); // For (INT I = 0; storefile. exists (); I ++) {// storefile = new file (storedir + separator + filename + I); //} bufferedoutputstream Bos = NULL; buff Eredinputstream Bis = NULL; try {Bos = new bufferedoutputstream (New fileoutputstream (storefile); Bis = new bufferedinputstream (in); int C; while (C = bis. read ())! =-1) {Bos. write (c); Bos. flush () ;}} catch (exception) {exception. printstacktrace (); throw new exception ("An error occurred while saving the file! ");} Finally {Bos. close (); bis. close () ;}/ *** prasemimemessage class test */public static void main (string ARGs []) throws exception {properties props = system. getproperties (); props. put ("mail. SMTP. host "," smtp.163.com "); props. put ("mail. SMTP. auth "," true "); Session session = session. getdefaultinstance (props, null); urlname urln = new urlname ("POP3", "pop3.163.com", 110, null, "xiangzhengyan", "pass"); store = session. getstore (urln); store. connect (); folder = store. getfolder ("inbox"); folder. open (folder. read_only); message [] = folder. getmessages (); system. out. println ("messages's length:" + message. length); reciveonemail PMM = NULL; For (INT I = 0; I <message. length; I ++) {system. out. println ("===================="); PMM = new reciveonemail (mimemessage) message [I]); system. out. println ("message" + I + "Subject:" + PMM. getsubject (); system. out. println ("message" + I + "sentdate:" + PMM. getsentdate (); system. out. println ("message" + I + "replysign:" + PMM. getreplysign (); system. out. println ("message" + I + "hasread:" + PMM. isnew (); system. out. println ("message" + I + "containattachment:" + PMM. iscontainattach (Part) Message [I]); system. out. println ("message" + I + "form:" + PMM. getfrom (); system. out. println ("message" + I + "to:" + PMM. getmailaddress ("to"); system. out. println ("message" + I + "cc:" + PMM. getmailaddress ("cc"); system. out. println ("message" + I + "BCC:" + PMM. getmailaddress ("BCC"); PMM. setdateformat ("mm DD, YY"); system. out. println ("message" + I + "sentdate:" + PMM. getsentdate (); system. out. println ("message" + I + "message-ID:" + PMM. getmessageid (); // obtain the email content ================== PMM. getmailcontent (Part) Message [I]); system. out. println ("message" + I + "bodycontent: RN" + PMM. getbodytext (); PMM. setattachpath ("C: \"); PMM. saveattachment (Part) Message [I]) ;}}

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.