JavaMail parsing message content (Classic collection)

Source: Internet
Author: User

Import java.io.*;    Import java.text.*;    Import java.util.*;    Import javax.mail.*;       Import javax.mail.internet.*;        /** * There is an email that needs to create a Recivemail object */public class Reciveonemail {private mimemessage mimemessage = null; Private String Saveattachpath = ""; Attachment download after the storage directory private StringBuffer bodytext = new StringBuffer ();//store the message content private String DateFormat = "yy-mm- DD hh:mm ";        The default display format public reciveonemail (MimeMessage mimemessage) {this.mimemessage = MimeMessage;        } public void Setmimemessage (MimeMessage 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 (personal = = null) personal = "";            String fromaddr = personal + "<" + from + ">";        return fromaddr; }/** * Get mail to the recipient, Cc, and Bcc address and name, depending on the parameters passed "to"----the recipient "CC"---cc address "BCC"---secret address */public S            Tring 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.reci                pienttype.cc);                } else {address = (internetaddress[]) mimemessage.getrecipients (Message.RecipientType.BCC);               } if (address! = null) {for (int i = 0; i < address.length; i++) {String EMA                        Il = 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 Message subject */public String Getsubject () throws Messagingexception {string subject = ""            ;                try {subject = Mimeutility.decodetext (Mimemessage.getsubject ());            if (subject = = null) Subject = "";        } catch (Exception exce) {} return subject; /** * Get mail sent date */public String getsentdate () throws Exception {Date sentdate            = Mimemessage.getsentdate ();            SimpleDateFormat format = new SimpleDateFormat (DateFormat);        Return Format.format (sentdate);        /** * Get message body contents */Public String Getbodytext () {return bodytext.tostring (); /** * Parse the message, save the resulting message content to a StringBuffer object, resolve the message is mainly based on the different types of mimetype to perform different operations, step by step resolution */PUB            LIC void Getmailcontent (part 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.getcont            ENT ());                } else if (Part.ismimetype ("multipart/*")) {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 {}}/** * To determine if this message requires a receipt, return "false" */public B If a receipt is required to return "true"Oolean getreplysign () throws Messagingexception {Boolean replysign = false;            String needreply[] = mimemessage. GetHeader ("disposition-notification-to");            if (needreply! = null) {replysign = true;        } return replysign;            /** * Get this message Message-id */public String Getmessageid () throws Messagingexception {        return Mimemessage.getmessageid (); }/** * "Determines if this message is read, if unread returns false, and vice versa returns true" */public Boolean isnew () throws Messagingexcepti            on {Boolean isnew = false;            Flags 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 = Tru                    E System.out.println ("SeeN Message ... ");                Break        }} return isnew;            /** * To determine if this message contains an attachment */public boolean Iscontainattach (parts 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; }}} and Else if (Part.ismimetype ("message/rfc822")) {Attachflag = Iscontainattach (            (part) part.getcontent ());        } return Attachflag; }/** * "Save Attachment" */public void saveattachment (parts part) throws Exception {Str            ing fileName = "";                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))))                        {fileName = Mpart.getfilename (); if (Filename.tolowercase (). IndexOf ("gb2312")! =-1) {fileName = Mimeutility.decodetext (Filenam                        e);                    } 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 Attachment storage Path" */public void Setattachpath (String attachpath) {        This.saveattachpath = Attachpath;            }/** * "Set date display format" */public void Setdateformat (String format) throws Exception {        This.dateformat = format;        }/** * "Get Attachment Storage Path" */public String Getattachpath () {return saveattachpath;  }/** * "True save attachment to 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;           Bufferedinputstream 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) {exception.printstacktrace ();           throw new Exception ("File save failed!");               } 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", +, NULL, "Xiangzhengyan", "pass");           Store store = Session.getstore (URLN);           Store.connect ();           Folder folder = Store.getfolder ("INBOX");           Folder.open (folder.read_only);           Message 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 ("yy years mm month DD Day hh:mm");               System.out.println ("Message" + i + "sentdate:" + pmm.getsentdate ()); System.out.println ("Message" + i + "Message-id: "+ Pmm.getmessageid ());               Get Mail Content =============== pmm.getmailcontent ((part) message[i]);               System.out.println ("Message" + i + "bodycontent: \ r \ n" + pmm.getbodytext ());                Pmm.setattachpath ("c:\\");            Pmm.saveattachment ((part) message[i]); }        }    }

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JavaMail parsing message content (Classic collection)

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.