Get 163 e-mail messages and download attachments

Source: Internet
Author: User
Tags rfc822 all mail email account

Teacher request to get email content, sender, recipient, send time, etc., dump into Excel, and download the attachment of the message, through the online collection of information, sorting out the following code, just to achieve the function, the code is not optimized.

When using, only need to fill in their email account password can be

Paste the code below,

Package Ltg.defualt;import Java.io.file;import Java.io.fileoutputstream;import java.io.outputstream;import Ltg.helper.pop3receivemailtest;import Ltg.helper.helphandler;public class Test {/** * @param args */public static void Ma In (string[] args) {try   {   //output Excel   <strong><span style= "color: #ff6666;" >file fileWrite = new File ("D:/testwrite.xls"); </span>  </strong>filewrite.createnewfile ();   OutputStream osq = new FileOutputStream (fileWrite);   Helphandler.writeexcel (OSQ);  Helphandler handler=new Helphandler (OSQ); handler.receive ();}   catch (Exception e)   {   e.printstacktrace ();}}   }
What you get is the Testwrite.xls of the D-disk.

The two classes are as follows

Package Ltg.helper;import Java.io.ioexception;import Java.io.outputstream;import jxl.*;import jxl.write.*;import Jxl.write.biff.rowsexceededexception;import Java.util.properties;import Javax.mail.folder;import Javax.mail.message;import Javax.mail.messagingexception;import Javax.mail.session;import Javax.mail.Store;import Javax.mail.internet.mimemessage;public class Helphandler {static OutputStream osq;static Writableworkbook wwb;static Writablesheet ws;<span style= "Font-size:18px;color: #ff6666;"  ><strong>static String array[] = {"Subject", "Sender", "Recipient", "Send Time", "read", "message priority", "Do I need receipts", "message size", "Include Attachments", "message body" };</strong></span>public Helphandler (OutputStream os) throws IOException {this.osq = OS;} /** * Receive mail */public static void receive () throws Exception {//Prepare session information for connection server properties props = new properties ();p ROPS.SETPR Operty ("Mail.store.protocol", "POP3"); Agreement Props.setproperty ("Mail.pop3.port", "110"); Port Props.setproperty ("Mail.pop3.host", "pop3.163.com"); PoP3 Server//Create Session instance object Session session = Session.getinstance (props); Store store = Session.getstore ("POP3"); <span style= "font-size:32px;" ><span style= "color: #ff0000;" >store.connect ("163 email account", "password"); </span></span>//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.getunreadmessagecount ());//Because the POP3 protocol is unable to know the status of the message, the following results are always 0system.out.println ("Deleted messages:" + Folder.getdeletedmessagecount ()); SYSTEM.OUT.PRINTLN ("New mail:" + folder.getnewmessagecount ());//Get the total number of messages in your Inbox System.out.println ("Total messages:" + Folder.getmessagecount ());//Get all mail in Inbox and parse message[] messages = Folder.getmessages ();p arsemessage (messages);// Frees resource Folder.close (true); Store.close ();} /** * Parse Mail * * @param messages * Mailing list to parse * @throws writeexception * @throws rowsexceededexception */public St atic void Parsemessage(Message ... messages) throws Messagingexception, IOException, rowsexceededexception,writeexception {if (Messages = = null | | Messages.length < 1) throw new Messagingexception ("Mail not found to resolve!"); try {WWB = Workbook.createworkbook (OSQ);//create Excel worksheet specify name and location WS = Wwb.createsheet ("Test Sheet 1", 0);//************** go to work Table Add data *****************//"unread messages", "Deleted Messages", "New Mail", "Total Messages",//write header for (int i = 0; i < Array.Length; i++) {Label labe1 = New Label (i, 0, array[i]); Ws.addcell (LABE1);} Resolve all messages for (int i = 0, count = messages.length; i < count; i++) {mimemessage msg = (mimemessage) messages[i]; System.out.println ("------------------parse" + msg.getmessagenumber () + "email--------------------"); Boolean B1 = Pop3receivemailtest.isseen (msg); Boolean iscontainerattachment = Pop3receivemailtest.iscontainattachment (msg); Boolean b2=pop3receivemailtest.isreplysign (msg); String str1 = ""; String str2 = ""; String STR3 = "", if (B1) str1 = "Yes", ELSESTR1 = "No", if (iscontainerattachment) STR3 = "Yes"; ELSESTR3 = "No"; if (B2) str2 = "Yes"; elsestr2 = "no"; StringBuffer content = new StringBuffer (30); Pop3receivemailtest.getmailtextcontent (msg, content); String array1[] = {pop3receivemailtest.getsubject (msg), Pop3receivemailtest.getfrom (msg), Pop3receivemailtest.getreceiveaddress (msg, NULL), Pop3receivemailtest.getsentdate (msg, NULL), STR1, Pop3receivemailtest.getpriority (msg), Str2,msg.getsize () * 1024x768 + "KB", STR3, content.tostring ()};str1 = ""; str2 = ""; str 3 = ""; for (int j = 0; J < Array1.length; J + +) {Label labe2 = new Label (j, i + 1, array1[j]); Ws.addcell (labe2);} System.out.println ("Subject:" + Pop3receivemailtest.getsubject (msg)); System.out.println ("sender:" + pop3receivemailtest.getfrom (msg)); System.out.println ("Recipient:" + pop3receivemailtest.getreceiveaddress (msg, null)); SYSTEM.OUT.PRINTLN ("Send time:" + pop3receivemailtest.getsentdate (msg, null)); System.out.println ("read:" + pop3receivemailtest.isseen (msg)); SYSTEM.OUT.PRINTLN ("Message priority:" + pop3receivemailtest.getpriority (msg)); System.out.println ("Do I Need a receipt:" + pop3receivemailtEst.isreplysign (msg)); SYSTEM.OUT.PRINTLN ("message size:" + msg.getsize () * 1024x768 + "KB"); System.out.println ("contains attachments:" + iscontainerattachment); if (iscontainerattachment) {<span style= "font-size:24px;" ><strong>pop3receivemailtest.saveattachment (msg, "d:\\mailtmp\\" + msg.getsubject () + "_"); Save Attachments </strong></span>}//StringBuffer content = new StringBuffer (30);// Pop3receivemailtest.getmailtextcontent (msg, content);//SYSTEM.OUT.PRINTLN ("message body:" + (Content.length () > 100?/) Content.substring (0,100) + "...": content); SYSTEM.OUT.PRINTLN ("message body:" + content); System.out.println ("------------------" + msg.getmessagenumber () + "End of email parsing--------------------"); System.out.println ();} write worksheet Wwb.write (); Wwb.close ();} catch (Exception e) {e.printstacktrace ();}}}
String array[] = {"Subject", "Sender", "Recipient", "Send Time", "is read", "message priority", "Do I need receipts", "message Size", "contains attachments", "Message body"}; This is an Excel table in which the field order is not variable and is consistent with the following order. download the relevant documents and pictures under the Mailtmp folder in D-Drive

Package Ltg.helper;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;import 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;/** * Receive mail using POP3 protocol */public class pop3receivemailtest {/** * Get message subject * * @param MSG * Message contents * @return decoded message subject */public static String Getsubject (M Imemessage msg) throws Unsupportedencodingexception, Messagingexception {return Mimeutility.decodetext (Msg.getsubject ());} /** * Get Mail Sender * * @param MSG * Message contents * @return Name <email address > * @throws messagingexception * @throws Unsupp Ortedencodingexception */public static String Getfrom (MimeMessage msg) throws Messagingexception, unsupportedencodingexception {String from = ""; address[] froms = Msg.getfrom (); if (Froms.length < 1) throw new Messagingexception ("No sender!"); I Nternetaddress 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 * &L            t;/p> * <p> * Message.RecipientType.BCC bcc * </p> * * @param MSG * Message contents * @param type * Recipient type * @return Recipient 1 < e-mail address 1>, Recipient 2 < mail toAddress 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 recipients!"); 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 STA Tic String getsentdate (mimemessage msg, string pattern) throws Messagingexception {Date receiveddate = 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 an attachment is included in the message * * @param MSG * Message contents * @return Message exists attachment returns TRUE, there is no return false * @throws Messagingexception * @thr oWS 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;} /** * Determine if the message has been read * * @param MSG * Message contents * @return If the message is read back true, return false * @throws Messagingexception */public St atic boolean Isseen (MimeMessage msg) throws Messagingexception {return msg.getflags (). Contains (Flags.Flag.SEEN);} /** * Determine if the message needs to read receipts * * @param MSG * Message contents * @return Need receipts return true, otherwise return 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;} /** * Receive Message priority * * @param MSG * message content * @return 1 (High): Emergency 3: Normal (normal) 5: lo (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 = "emergency"; else if (headerpriority . IndexOf ("5")! = -1| | Headerpriority.indexof ("low")! =-1) Priority = "lower"; elsepriority = "normal";} return priority;}  /** * Get Message text content * * @param part * message body * @param content * String that stores message text content * @throws messagingexception * @throws ioexception */public static void Getmailtextcontent (part part, StringBuffer content) throws Messagingexception, I oexception {//If it is a text type of attachment, the GetContent method can be used to get the text content, but this is not the result we need, so here to make a decision 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-1;i++) {BodyPart bodypart = Multipart.getbodypart (i); Getmailtextcontent (bodypart, content);}}} /** * Save Attachments * * @param part * A combination of multiple compositions in a message * @param destDir * Attachments Save directory * @throws unsupportedencod Ingexception * @throws messagingexception * @throws filenotfoundexception * @throws ioexception */public static void Savea Ttachment (part part, String DestDir) throws Unsupportedencodingexception, Messagingexception,filenotfoundexception, IOException {if (Part.ismimetype ("multipart/*")) {multipart multipart = (multipart) part.getcontent ();//complex mail// 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 Bodypa RT = Multipart.getbodypart (i);//A message body may also be a complex body composed of multiple mail bodies string disp = Bodypart.getdisposition (); if (disp! = null&& Amp (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 the data from the input stream to the specified directory * * @param is * input stream * @param filename * filename * @param destDir * file Storage directory * @throws filenotfoundexception * @throws ioexception */private static void SaveFile (InputStream is, String DestDir, String fileName) throws FileNotFoundException, IOException {Bufferedinputstream bis = new Bufferedinputstream (IS); Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (New File (DestDir + fileName)); int len = -1;whil E (len = Bis.read ())! =-1) {bos.write (len); Bos.flush ();} Bos.close (); Bis.close ();}          /** * Text decoding * * @param encodetext *  Decodes the Mimeutility.encodetext (String text) method after encoding the text * @return decoded text * @throws unsupportedencodingexception */public static St Ring Decodetext (String encodetext) throws Unsupportedencodingexception {if (Encodetext = = NULL | | ". Equals (Encodetext)) {return" ";} else {return mimeutility.decodetext (Encodetext);}}}


need to import two jar packages


Https://yunpan.cn/cqj2hyXEUf5fQ Access Password 6ACC

Https://yunpan.cn/cqj27LI3kjBbU Access Password 3712





Get 163 e-mail messages and download attachments

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.