Some time ago has been busy school inside things, there is no time to write down the heart of the program to receive mail, now the school of things finally busy, you can calm down to do what they like to do, this feeling really good!
For myself, the most important and hardest thing to do when I started using JavaMail to write a mail-receiving program was to parse the attachments and the body of the message because there were so many MIME types! The following code is my own learning javamail a piece of experience, for everyone to refer to (please master advice, what a better way, please reply to this article), the specific code is as follows:
Package coffeecatwebmail;
Import java.io.*;
Import java.text.*;
Import java.util.*;
Import javax.mail.*;
Import javax.mail.internet.*;
public class prasemimemessage{Private mimemessage mimemessage = null; Private String Saveattachpath = "";
Attachment download after the storage directory private StringBuffer bodytext = new StringBuffer (); The StringBuffer object that holds the message content is private String DateFormat = "Yy-mm-dd hh:mm"; The default date display format/** * constructor, Initializes a MimeMessage object/public Prasemimemessage () {} public prasemimemessage (MimeMessage Mimemessa
GE) {this.mimemessage = MimeMessage;
System.out.println ("Create a Prasemimemessage object ...");
public void Setmimemessage (MimeMessage mimemessage) {this.mimemessage = MimeMessage; /** * Get sender's address and name//public String Getfrom () throws exception{internetaddress address[] = (internetaddress[)) Mimeme
Ssage.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; /** * Obtain the recipient, Cc, and Bcc address and name of the message, depending on the parameters passed * "to"----recipient "CC"---cc address "bcc"---the BCC address/public String getmailaddress (Str
ing 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.R
ECIPIENTTYPE.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 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 Send date/public String getsentdate () throws exception{Date sentdate = Mimemessage.getsentdate ();
SimpleDateFormat format = new SimpleDateFormat (DateFormat);
Return Format.format (sentdate);
/** * Get message body content/public String Getbodytext () {return bodytext.tostring (); /** * parsing mail, the resulting message content to a StringBuffer object, parsing mail * mainly based on the different types of mimetype to perform different operations, step-by-Step analysis/public 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.getcontent ());
}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 the message requires a receipt, return "true" if the receipt is required, or "false"/public boolean getreplysign () throws Messagingexceptio
n{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.getmessage
ID (); /** * "Determines if this message is read and returns False if unread returns true" */public Boolean isnew () throws messagingexception{Boolean isnew = f
Alse;
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=true;
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;
}}else if (Part.ismimetype ("message/rfc822")) {Attachflag = Iscontainattach ((part) part.getcontent ());
return attachflag;
/** * "Save Attachment"/public void Saveattachment (parts 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.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 (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 (f
Ilename);
SaveFile (Filename,mpart.getinputstream ());
}}}else if (Part.ismimetype ("message/rfc822")) {Saveattachment ((part) part.getcontent ());}
/** * "Set attachment store 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 path" */public String Getattachpath () {return savEattachpath; /** * "Real save attachment to specified directory"/private void SaveFile (String Filename,inputstream in) throws exception{String Osname = Sys
Tem.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{String host = "Host name/IP"; "pop.mail.yahoo.com.cn" String username = "User name"; "wwp_1124" String password = "password";
"..." Properties props = new properties ();
Session session = Session.getdefaultinstance (props, null);
Store store = Session.getstore ("POP3");
Store.connect (host, username, password);
Folder folder = Store.getfolder ("INBOX");
Folder.open (folder.read_only);
Message message[] = Folder.getmessages ();
System.out.println ("Messages ' s Length:" +message.length);
Prasemimemessage PMM = null;
for (int i=0;i<message.length;i++) {pmm = new Prasemimemessage ((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 year mm month DD Day hh:mm");
SYSTEM.OUT.PRINTLN ("message" +i+ "Sentdate:" +pmm.getsentdate ());
SYSTEM.OUT.PRINTLN ("message" +i+ "Message-id:" +pmm.getmessageid ());
Pmm.getmailcontent ((part) message[i]);
SYSTEM.OUT.PRINTLN ("message" +i+ "bodycontent: \ r \ n" +pmm.getbodytext ());
Pmm.setattachpath ("c:\\tmp\\coffeecat1124");
Pmm.saveattachment ((part) message[i]); } } }
The above is to use JavaMail to parse the specific program code of the MimeMessage, the specific use of the method reference in the main method of the test code, please see more than to mention the valuable advice, common learning and common growth!!