日期:2008-12-19  浏览次数:20790 次

附录:ListServer.java
/**
* 类ListServer提供基本的邮件列表服务功能:读取指定邮件帐号的所有新邮件,然后转发给
* 在emailListFile文件中指定的所有邮件帐号(订阅者).emailListFile中的邮件帐号格式

* 为每一行一个邮件帐号.
*/
import java.util.*;
import java.io.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class Class1
{
private static final String INBOX = "INBOX", POP_MAIL="pop3", SMTP_MAIL="smtp";
private boolean debugOn = false;
private String _smtpHost = null,
_pop3Host = null,
_user = null,
_password = null,
_emailListFile = null,
_fromName = null;
private InternetAddress[] _toList = null;

//main():创建和启动ListServer实例
public static void main(String args[])
throws Exception
{
//检查输入参数
if (args.length < 6)
{
System.err.println("Usage: java ListServer SMTP服务器 POP3服务器 POP3帐号 POP3帐号密码 订阅者清单文件 检查周期(分钟) 发信人名称");
System.exit(1);
}

// 将命令行参数赋值给对应的变量
String smtpHost = args[0], //smtp服务器
pop3Host = args[1], //pop3服务器
user = args[2], //pop3邮件帐号
password = args[3], //pop3邮件帐号密码
emailListFile=args[4], //订阅者清单文件
fromName = null; //发信人名称

int checkPeriod = Integer.parseInt(args[5]); //新邮件检查周期

if (args.length > 6)
fromName = args[6];

// 创建ListServer实例,循环处理新邮件
ListServer ls = new ListServer();
ls.setDebug(false);
while (true)
{
ls.debugMsg("ListServer启动...");
ls.process(smtpHost, pop3Host, user, password, emailListFile, fromName);
ls.debugMsg("ListServer暂停 (休息 " + checkPeriod + " 分钟)");
Thread.sleep(checkPeriod*1000*60);
}
}


// process(): 检查新邮件,调用 processMsg() 处理单个邮件
public void process(String smtpHost, String pop3Host, String user, String password, String emailListFile, String fromName)
throws Exception
{
_smtpHost = smtpHost;
_pop3Host = pop3Host;
_user = user;
_password = password;
_emailListFile = emailListFile;
if (fromName != null)
_fromName = fromName;

// 将订阅者帐号读入 java.util.Vector
Vector vList = new Vector(10);
BufferedReader listFile = new BufferedReader(new FileReader(emailListFile));
String line = null;
while ((line = listFile.readLine()) != null)
{
vList.addElement(new InternetAddress(line));
}
listFile.close();

debugMsg("共计 " + vList.size() + " 个订阅者");

_toList = new InternetAddress[vList.size()];
vList.copyInto(_toList);
vList = null;

// 获得 Session 对象
Properties sysProperties = System.getProperties();
Session session = Session.getDefaultInstance(sysProperties, null);
session.setDebug(debugOn);

// 连接POP3邮件服务器
Store store = session.getStore(POP_MAIL);
store.connect(pop3Host, -1, _user, _password);

// 打开缺省文件夹
Folder folder = store.getDefaultFolder();
if (folder == null)
throw new NullPointerException("没有缺省邮件文件夹");
folder = folder.getFolder(INBOX);
if (folder == null)
throw new NullPointerException("无法打开文件夹: " + folder);
folder.open(Folder.READ_WRITE);

// 获得新邮件数
int totalMessages = folder.getMessageCount();
if (totalMessages == 0)
{
debugMsg(folder + " 没有新邮件");
folder.close(false);
store.close();
return;
}

// 获得所有新邮件的属性和标记
Message[] messages = folder.getMessages();
FetchProfile fp =