JavaMail快速入门__教程 |
|
日期:2007-5-20 0:38:42 人气:317 [大 中 小] |
|
|
|
实际上,当你看过SimpleReceiver类的代码之后,你会发现一切都变得很明朗。我们用三部分内容来介绍SimpleReceiver类:第一部分,类的定义以及从命令行获取连接细节信息的main()方法;第二部分,捕获和查看进来消息的receive()方法;第三部分,打印头信息和每个消息内容的printMessage()方法。 下面是第一部分: package com.lotontech.mail; import javax.mail.*; import javax.mail.internet.*; import java.util.*; import java.io.*; /** * A simple email receiver class. */ public class SimpleReceiver { /** * Main method to receive messages from the mail server specified * as command line arguments. */ public static void main(String args[]) { try { String popServer=args[0]; String popUser=args[1]; String popPassword=args[2]; receive(popServer, popUser, popPassword); } catch (Exception ex) { System.out.println("Usage: java com.lotontech.mail.SimpleReceiver" +" popServer popUser popPassword"); } System.exit(0); } 现在我们使用命令行来运行它(记住用你的email设置替换命令行参数): java com.lotontech.mail.SimpleReceiver pop.myIsp.net myUserName myPassword
receive()方法从main()方法中调用,它依次打开你的POP3信箱检查消息,每次都调用printMessage()。代码如下:
/**
* "receive" method to fetch messages and process them.
*/
public static void receive(String popServer, String popUser
, String popPassword)
{
Store store=null;
Folder folder=null;
try
{
// -- Get hold of the default session --
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
// -- Get hold of a POP3 message store, and connect to it --
store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);
// -- Try to get hold of the default folder --
folder = store.getDefaultFolder();
if (folder == null) throw new Exception("No default folder");
// -- ...and its INBOX --
folder = folder.getFolder("INBOX");
if (folder == null) throw new Exception("No POP3 INBOX");
// -- Open the folder for read only --
folder.open(Folder.READ_ONLY);
// -- Get the message wrappers and process them --
Message[] msgs = folder.getMessages();
for (int msgNum = 0; msgNum < msgs.length; msgNum++)
{
printMessage(msgs[msgNum]);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
// -- Close down nicely --
try
{
if (folder!=null) folder.close(false);
if (store!=null) store.close();
}
catch (Exception ex2) {ex2.printStackTrace();}
}
}
请注意:你从session中得到一个POP3消息存储封装器,然后使用最初在命令行上键入的mail设置跟它连接。
一旦连接成功,你就得到了一个默认文件夹的句柄,在这里使用的是INBOX文件夹,它保存了进来的消息。你可以打开这个只读的INBOX信箱,然后一个一个的读取消息。
另外,你可能想知道是否你能够以写的方式打开这个INBOX信箱。如果你想为这些消息做标记或者从服务器上删除,你可以做得到。不过在我们的这个例子中,你只能查看消息。 |
|
出处:本站原创 作者:佚名 |
|
|