请注意:你从session中得到一个pop3消息存储封装器,然后使用最初在命令行上键入的mail设置跟它连接。
一旦连接成功,你就得到了一个默认文件夹的句柄,在这里使用的是inbox文件夹,它保存了进来的消息。你可以打开这个只读的inbox信箱,然后一个一个的读取消息。
另外,你可能想知道是否你能够以写的方式打开这个inbox信箱。如果你想为这些消息做标记或者从服务器上删除,你可以做得到。不过在我们的这个例子中,你只能查看消息。
最后,在上面的代码中,你做到了当查看完毕后关闭文件夹以及消息存储,然后留下printmessage()方法来完成这个类的剩余部分。
打印消息
在这一部分,很有必要讨论前面提到的javax.mail.part接口。
下面的代码让你明白怎样隐含地把消息转换为它的part接口并且把它赋给messagepart变量。对于只有一部分的消息,你现在需要打印一些信息。
假如调用messagepart.getcontent()来生成一个multipart实例,你知道你正在处理一个多部分消息;在这种情况下,你正在通过getbodypart(0)来得到第一个多部分消息并且打印它。
当然你还要知道是否你已经得到了这个消息本身,还是仅仅是消息正文的第一部份。只有当内容是普通文本或者html时,你才可以打印该消息,这是通过一个inputstream来完成的。
/**
* "printmessage()" method to print a message.
*/
public static void printmessage(message message)
{
try
{
// get the header information
string from=((inte.netaddress)message.getfrom()[0]).getpersonal();
if (from==null) from=((inte.netaddress)message.getfrom()[0])
.getaddress();
system.out.println("from: "+from);
string subject=message.getsubject();
system.out.println("subject: "+subject);
// -- get the message part (i.e. the message itself) --
part messagepart=message;
object content=messagepart.getcontent();
// -- or its first body part if it is a multipart message --
if (content instanceof multipart)
{
messagepart=((multipart)content).getbodypart(0);
system.out.println("[ multipart message ]");
}
// -- get the content type --
string contenttype=messagepart.getcontenttype();
// -- if the content is plain text, we can print it --
system.out.println("content:"+contenttype);
if (contenttype.startswith("text/plain") contenttype.startswith("text/html"))
{
inputstream is = messagepart.getinputstream();
bufferedreader reader=new bufferedreader(new inputstreamreader(is));
string thisline=reader.readline();
while (thisline!=null)
{
system.out.println(thisline);
thisline=reader.readline();
}
}
system.out.println("-----------------------------");
}
catch (exception ex)
{
ex.printstacktrace();
}
}
}
为了简单起见,我假设消息本身或者消息正文的第一部份是可以打印的。对于真正的应用软件,可能你想要依次检查消息正文的每一部分,并且对每一部分采取相应的行动-打印或者是保存到磁盘,这取决于内容的类型。
当你从消息存储中得到每个消息时,你实际上已经得到了一个轻量级的封装器。数据内容的获取是每申请一次就读取一次-这对于你只想下载消息头时很有用。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器