import
javax.mail.Store;
import
javax.mail.
*
;
import
java.io.BufferedReader;
import
java.io.InputStreamReader;
import
java.io.
*
;
/**
*
* <p>Title: JavaMail</p>
* <p>Description:收取邮件 </p>
* <p>Copyright: Copyright (c) 2005</p>
*
@author
Derek.G
*
@version
1.0
* 收取邮件:
1.获取一个会话;
2.获取并连接邮箱所在的存储器(Store对象),打开该用户的邮箱;
3.获取所希望阅读的消息;
4.关闭目录和连接。
*/
public
class
ReadMail
extends
MailProcessBase{
//
初始化主机
String host
=
"
pop3.usish.com
"
;
String username
=
"
derek_g
"
;
String password
=
"
12140827
"
;
public
ReadMail()
throws
Exception {
super
();
}
public
void
readMail(){
try
{
//
获取Store对象,使用POP3协议,也可能使用IMAP
System.out.println(
"
获取Store对象
"
);
Store store
=
mailSession.getStore(
"
pop3
"
);
//
连接到邮件服务器
System.out.println(
"
连接到邮件服务器
"
);
store.connect(host, username, password);
//
获取该用户Folder对象,并以只读方式打开
System.out.println(
"
获取该用户Folder对象
"
);
Folder folder
=
store.getFolder(
"
INBOX
"
);
folder.open(Folder.READ_ONLY);
//
检索所有邮件,按需填充
System.out.println(
"
检索所有邮件
"
);
Message message[]
=
folder.getMessages();
//
遍历每一个邮件
System.out.println(
"
遍历每一个邮件
"
);
BufferedReader reader
=
new
BufferedReader(
new
InputStreamReader(System.in));
for
(
int
i
=
0
, n
=
message.length; i
<
n; i
++
) {
//
打印每个邮件的发件人和主题
System.out.println(i
+
"
:
"
+
message[i].getFrom()[
0
]
+
"
\t
"
+
message[i].getSubject());
//
是否读取该消息
System.out.println(
"
是否读取消息内容?
"
+
"
[YES读取 / QUIT结束]
"
);
String line
=
reader.readLine();
FileOutputStream fos
=
new
FileOutputStream(
"
c:\\mail.txt
"
);
if
(line.equals(
"
YES
"
)) {
message[i].writeTo(fos);
//
这种方式只能显示文本消息
System.out.println(message[i].getContent());
}
else
break
;
}
System.out.println(
"
收取邮件完毕!
"
);
folder.close(
false
);
store.close();
}
catch
(NoSuchProviderException ex) {ex.printStackTrace();}
catch
(MessagingException ex) {ex.printStackTrace();}
catch
(IOException ex) { ex.printStackTrace(); }
}
public
static
void
main(String[] args) {
try
{
new
ReadMail().readMail();
}
catch
(Exception ex) {ex.printStackTrace(); }
}
}
posted on 2006-03-24 17:03
Derek.Guo 阅读(329)
评论(0) 编辑 收藏 所属分类:
Java