Import java.io.*;
Import java.text.*;
Import java.util.*;
Import javax.mail.*;
Import javax.mail.internet.*;
/**
* One e-mail will need to create a Recivemail object
*/
public class Reciveonemail {
Private MimeMessage mimemessage = null;
Private String Saveattachpath = ""; Storage directory after download of attachments
Private StringBuffer BodyText = new StringBuffer ();//Store mail contents
Private String DateFormat = "Yy-mm-dd hh:mm"; Default display format for the day before
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;
}
/**
* The recipient, CC, and Bcc address and name of the message, depending on the parameters passed, "to"----the recipient "CC"---cc address "bcc"---secret delivery 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 e-mail delivery date
*/
Public String getsentdate () throws Exception {
Date sentdate = Mimemessage.getsentdate ();
SimpleDateFormat format = new SimpleDateFormat (DateFormat);
Return Format.format (sentdate);
}
/**
* Get the message body content
*/
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 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 a receipt is required, or "false"
*/
public Boolean getreplysign () throws Messagingexception {
Boolean replysign = false;
String needreply[] = MimeMessage
. GetHeader ("disposition-notification-to");
if (needreply! = null) {
Replysign = true;
}
return replysign;
}
/**
* Get Message-id of this email
*/
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 Messagingexception {
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 = true;
System.out.println ("Seen Message ...");
Break
}
}
return isnew;
}
/**
* Determine if this message contains attachments
*/
public boolean Iscontainattach (part 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 Attachments"
*/
public void Saveattachment (part 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 (filename);
SaveFile (FileName, Mpart.getinputstream ());
}
}
}
} else if (Part.ismimetype ("message/rfc822")) {
Saveattachment ((part) part.getcontent ());
}
}
/**
* "Set attachments to 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 Storage Path"
*/
Public String Getattachpath () {
return saveattachpath;
}
/**
* "Real save attachments 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;
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 Email content ===============
Pmm.getmailcontent ((part) message[i]);
System.out.println ("Message" + i + "bodycontent: \ r \ n"
+ Pmm.getbodytext ());
Pmm.setattachpath ("c:\\");
Pmm.saveattachment ((part) message[i]);
}
}
}
< >javamail receive mail (more than a full)