1、showmsg
指定一个文件夹如INBOX(收件箱),打印出该文件夹下面所有的邮件信息:
public
class MyTest3 {
static String indentStr = " ";
static int level = 0;
static int attnum = 1;
public static void showMsg() throws Exception {
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore( new URLName( "imap://test:[email protected]"));
store.connect();
String mbox = "INBOX";
Folder folder = store.getDefaultFolder();
folder = folder.getFolder(mbox);
folder.open(Folder.READ_ONLY);
int totalMessages = folder.getMessageCount();
int newMessages = folder.getNewMessageCount();
System.out.println( "Total messages = " + totalMessages);
System.out.println( "New messages = " + newMessages);
Message[] msgs = folder.getMessages();
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add( "X-Mailer");
folder.fetch(msgs, fp);
for ( int i = 0; i < msgs.length; i++) {
System.out.println( "--------------------------");
System.out.println( "MESSAGE #" + (i + 1) + ":");
dumpPart2(msgs[i]);
}
static String indentStr = " ";
static int level = 0;
static int attnum = 1;
public static void showMsg() throws Exception {
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore( new URLName( "imap://test:[email protected]"));
store.connect();
String mbox = "INBOX";
Folder folder = store.getDefaultFolder();
folder = folder.getFolder(mbox);
folder.open(Folder.READ_ONLY);
int totalMessages = folder.getMessageCount();
int newMessages = folder.getNewMessageCount();
System.out.println( "Total messages = " + totalMessages);
System.out.println( "New messages = " + newMessages);
Message[] msgs = folder.getMessages();
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add( "X-Mailer");
folder.fetch(msgs, fp);
for ( int i = 0; i < msgs.length; i++) {
System.out.println( "--------------------------");
System.out.println( "MESSAGE #" + (i + 1) + ":");
dumpPart2(msgs[i]);
}
store.close();
}
public static void dumpPart2(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message) p);
String ct = p.getContentType();
pr( "CONTENT-TYPE: " + ( new ContentType(ct)).toString());
String filename = p.getFileName();
if (filename != null)
pr( "FILENAME: " + filename);
// 打印出内容:
if (p.isMimeType( "text/plain")) {
pr( "This is plain text");
pr( "---------------------------");
System.out.println((String) p.getContent());
} else if (p.isMimeType( "multipart/*")) {
pr( "This is a Multipart");
pr( "---------------------------");
Multipart mp = (Multipart) p.getContent();
level++;
int count = mp.getCount();
for ( int i = 0; i < count; i++)
dumpPart2(mp.getBodyPart(i));
level--;
} else if (p.isMimeType( "message/rfc822")) {
pr( "This is a Nested Message");
pr( "---------------------------");
level++;
dumpPart1((Part) p.getContent());
level--;
} else {
// 这里也可以采用注释掉的方式输出,缺点是会把附件内容也用流的方式打印出来:
// Object o = p.getContent();
// if (o instanceof String) {
// pr("This is a string");
// pr("---------------------------");
// System.out.println((String) o);
// } else if (o instanceof InputStream) {
// pr("This is just an input stream");
// pr("---------------------------");
// InputStream is = (InputStream) o;
// int c;
// while ((c = is.read()) != -1)
// System.out.write(c);
// } else {
// pr("This is an unknown type");
// pr("---------------------------");
// pr(o.toString());
// }
pr( "---------------------------");
}
// 处理附件
if (level != 0 && !p.isMimeType( "multipart/*")) {
String disp = p.getDisposition();
if (filename != null && (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT))) {
pr( "Saving p_w_upload to file " + filename);
try {
File f = new File(filename);
if (f.exists())
throw new IOException( "file exists");
((MimeBodyPart) p).saveFile(f);
} catch (IOException ex) {
pr( "Failed to save p_w_upload: " + ex);
}
pr( "---------------------------");
}
}
}
public static void dumpEnvelope(Message m) throws Exception {
pr( "This is the message envelope");
pr( "---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for ( int j = 0; j < a.length; j++)
pr( "FROM: " + a[j].toString());
}
// REPLY TO
if ((a = m.getReplyTo()) != null) {
for ( int j = 0; j < a.length; j++)
pr( "REPLY TO: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for ( int j = 0; j < a.length; j++) {
pr( "TO: " + a[j].toString());
InternetAddress ia = (InternetAddress) a[j];
if (ia.isGroup()) {
InternetAddress[] aa = ia.getGroup( false);
for ( int k = 0; k < aa.length; k++)
pr( " GROUP: " + aa[k].toString());
}
}
}
// SUBJECT
pr( "SUBJECT: " + m.getSubject());
// DATE
Date d = m.getSentDate();
pr( "SendDate: " + (d != null ? d.toString() : "UNKNOWN"));
// FLAGS
Flags flags = m.getFlags();
StringBuffer sb = new StringBuffer();
Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
boolean first = true;
for ( int i = 0; i < sf.length; i++) {
String s;
Flags.Flag f = sf[i];
if (f == Flags.Flag.ANSWERED)
s = "\\Answered";
else if (f == Flags.Flag.DELETED)
s = "\\Deleted";
else if (f == Flags.Flag.DRAFT)
s = "\\Draft";
else if (f == Flags.Flag.FLAGGED)
s = "\\Flagged";
else if (f == Flags.Flag.RECENT)
s = "\\Recent";
else if (f == Flags.Flag.SEEN)
s = "\\Seen";
else
continue; // skip it
if (first)
first = false;
else
sb.append(' ');
sb.append(s);
}
String[] uf = flags.getUserFlags(); // get the user flag strings
for ( int i = 0; i < uf.length; i++) {
if (first)
first = false;
else
sb.append(' ');
sb.append(uf[i]);
}
pr( "FLAGS: " + sb.toString());
// X-MAILER
String[] hdrs = m.getHeader( "X-Mailer");
if (hdrs != null)
pr( "X-Mailer: " + hdrs[0]);
else
pr( "X-Mailer NOT available");
}
public static void pr(String s) {
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}
public static void main(String[] args) {
try {
showMsg();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void dumpPart2(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message) p);
String ct = p.getContentType();
pr( "CONTENT-TYPE: " + ( new ContentType(ct)).toString());
String filename = p.getFileName();
if (filename != null)
pr( "FILENAME: " + filename);
// 打印出内容:
if (p.isMimeType( "text/plain")) {
pr( "This is plain text");
pr( "---------------------------");
System.out.println((String) p.getContent());
} else if (p.isMimeType( "multipart/*")) {
pr( "This is a Multipart");
pr( "---------------------------");
Multipart mp = (Multipart) p.getContent();
level++;
int count = mp.getCount();
for ( int i = 0; i < count; i++)
dumpPart2(mp.getBodyPart(i));
level--;
} else if (p.isMimeType( "message/rfc822")) {
pr( "This is a Nested Message");
pr( "---------------------------");
level++;
dumpPart1((Part) p.getContent());
level--;
} else {
// 这里也可以采用注释掉的方式输出,缺点是会把附件内容也用流的方式打印出来:
// Object o = p.getContent();
// if (o instanceof String) {
// pr("This is a string");
// pr("---------------------------");
// System.out.println((String) o);
// } else if (o instanceof InputStream) {
// pr("This is just an input stream");
// pr("---------------------------");
// InputStream is = (InputStream) o;
// int c;
// while ((c = is.read()) != -1)
// System.out.write(c);
// } else {
// pr("This is an unknown type");
// pr("---------------------------");
// pr(o.toString());
// }
pr( "---------------------------");
}
// 处理附件
if (level != 0 && !p.isMimeType( "multipart/*")) {
String disp = p.getDisposition();
if (filename != null && (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT))) {
pr( "Saving p_w_upload to file " + filename);
try {
File f = new File(filename);
if (f.exists())
throw new IOException( "file exists");
((MimeBodyPart) p).saveFile(f);
} catch (IOException ex) {
pr( "Failed to save p_w_upload: " + ex);
}
pr( "---------------------------");
}
}
}
public static void dumpEnvelope(Message m) throws Exception {
pr( "This is the message envelope");
pr( "---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for ( int j = 0; j < a.length; j++)
pr( "FROM: " + a[j].toString());
}
// REPLY TO
if ((a = m.getReplyTo()) != null) {
for ( int j = 0; j < a.length; j++)
pr( "REPLY TO: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for ( int j = 0; j < a.length; j++) {
pr( "TO: " + a[j].toString());
InternetAddress ia = (InternetAddress) a[j];
if (ia.isGroup()) {
InternetAddress[] aa = ia.getGroup( false);
for ( int k = 0; k < aa.length; k++)
pr( " GROUP: " + aa[k].toString());
}
}
}
// SUBJECT
pr( "SUBJECT: " + m.getSubject());
// DATE
Date d = m.getSentDate();
pr( "SendDate: " + (d != null ? d.toString() : "UNKNOWN"));
// FLAGS
Flags flags = m.getFlags();
StringBuffer sb = new StringBuffer();
Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
boolean first = true;
for ( int i = 0; i < sf.length; i++) {
String s;
Flags.Flag f = sf[i];
if (f == Flags.Flag.ANSWERED)
s = "\\Answered";
else if (f == Flags.Flag.DELETED)
s = "\\Deleted";
else if (f == Flags.Flag.DRAFT)
s = "\\Draft";
else if (f == Flags.Flag.FLAGGED)
s = "\\Flagged";
else if (f == Flags.Flag.RECENT)
s = "\\Recent";
else if (f == Flags.Flag.SEEN)
s = "\\Seen";
else
continue; // skip it
if (first)
first = false;
else
sb.append(' ');
sb.append(s);
}
String[] uf = flags.getUserFlags(); // get the user flag strings
for ( int i = 0; i < uf.length; i++) {
if (first)
first = false;
else
sb.append(' ');
sb.append(uf[i]);
}
pr( "FLAGS: " + sb.toString());
// X-MAILER
String[] hdrs = m.getHeader( "X-Mailer");
if (hdrs != null)
pr( "X-Mailer: " + hdrs[0]);
else
pr( "X-Mailer NOT available");
}
public static void pr(String s) {
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}
public static void main(String[] args) {
try {
showMsg();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出结果:
Total messages = 1
New messages = 0
--------------------------
MESSAGE #1:
This is the message envelope
---------------------------
FROM: test2 <[email][email protected][/email]>
REPLY TO: test2 <[email][email protected][/email]>
TO: test <[email][email protected][/email]>
SUBJECT: 测试邮件
SendDate: Mon Apr 20 21:42:53 CST 2009
FLAGS:
X-Mailer: Foxmail 6, 14, 103, 24 [cn]
CONTENT-TYPE: multipart/mixed; boundary="=====001_Dragon465810857202_====="
This is a Multipart
---------------------------
CONTENT-TYPE: text/plain; charset=gb2312
This is plain text
---------------------------
2009-04-20 是一个好日子啊!哈哈
CONTENT-TYPE: application/octet-stream; name=Noname1.txt
FILENAME: Noname1.txt
---------------------------
Saving p_w_upload to file Noname1.txt
---------------------------
CONTENT-TYPE: p_w_picpath/jpeg; name=m1.jpg
FILENAME: m1.jpg
---------------------------
Saving p_w_upload to file m1.jpg
---------------------------
New messages = 0
--------------------------
MESSAGE #1:
This is the message envelope
---------------------------
FROM: test2 <[email][email protected][/email]>
REPLY TO: test2 <[email][email protected][/email]>
TO: test <[email][email protected][/email]>
SUBJECT: 测试邮件
SendDate: Mon Apr 20 21:42:53 CST 2009
FLAGS:
X-Mailer: Foxmail 6, 14, 103, 24 [cn]
CONTENT-TYPE: multipart/mixed; boundary="=====001_Dragon465810857202_====="
This is a Multipart
---------------------------
CONTENT-TYPE: text/plain; charset=gb2312
This is plain text
---------------------------
2009-04-20 是一个好日子啊!哈哈
CONTENT-TYPE: application/octet-stream; name=Noname1.txt
FILENAME: Noname1.txt
---------------------------
Saving p_w_upload to file Noname1.txt
---------------------------
CONTENT-TYPE: p_w_picpath/jpeg; name=m1.jpg
FILENAME: m1.jpg
---------------------------
Saving p_w_upload to file m1.jpg
---------------------------
从输出结果可以看到,这份邮件由一个Multipart组成,其中又包含三个子Part:
第一个Part:邮件的正文,也即“2009-04-20 是一个好日子啊!哈哈”这句话。
第二个Part:附件“Noname1.txt”
第三个Part:图片“m1.jpg”
2、namespace(这个相对简单一些):
public
static
void namespace()
throws Exception {
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore( new URLName( "imap://test:[email protected]"));
store.connect();
printFolders( "Personal", store.getPersonalNamespaces());
printFolders( "User test", store.getUserNamespaces( "test"));
printFolders( "Shared", store.getSharedNamespaces());
store.close();
}
private static void printFolders(String name, Folder[] folders) throws MessagingException {
System.out.println(name + " Namespace:");
if (folders == null || folders.length == 0) {
System.out.println( "" );
return;
}
for ( int i = 0; i < folders.length; i++) {
String fn = folders[i].getFullName();
if (fn.length() == 0)
fn = "<default folder>";
try {
System.out.println( " " + fn + ", delimiter \"" + folders[i].getSeparator()
+ "\"");
Folder[] fl = folders[i].list();
if (fl.length > 0) {
System.out.println( " Subfolders:");
for ( int j = 0; j < fl.length; j++)
System.out.println( " " + fl[j].getFullName());
}
} catch (FolderNotFoundException ex) {
}
}
}
public static void main(String[] args) {
try {
namespace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore( new URLName( "imap://test:[email protected]"));
store.connect();
printFolders( "Personal", store.getPersonalNamespaces());
printFolders( "User test", store.getUserNamespaces( "test"));
printFolders( "Shared", store.getSharedNamespaces());
store.close();
}
private static void printFolders(String name, Folder[] folders) throws MessagingException {
System.out.println(name + " Namespace:");
if (folders == null || folders.length == 0) {
System.out.println( "
return;
}
for ( int i = 0; i < folders.length; i++) {
String fn = folders[i].getFullName();
if (fn.length() == 0)
fn = "<default folder>";
try {
System.out.println( " " + fn + ", delimiter \"" + folders[i].getSeparator()
+ "\"");
Folder[] fl = folders[i].list();
if (fl.length > 0) {
System.out.println( " Subfolders:");
for ( int j = 0; j < fl.length; j++)
System.out.println( " " + fl[j].getFullName());
}
} catch (FolderNotFoundException ex) {
}
}
}
public static void main(String[] args) {
try {
namespace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
输出结果:
Personal Namespace:
, delimiter "/"
Subfolders:
Sent
Draft
Trash
Spam
Backup
INBOX
User test Namespace:
Shared Namespace:
Subfolders:
Sent
Draft
Trash
Spam
Backup
INBOX
User test Namespace:
Shared Namespace: