用Java实现SMTP服务器

豆豆网   技术应用频道   2006年11月14日  【字号: 收藏本文

本文详细介绍用Java实现SMTP服务器

cmdExit.addActionListener(newjava.awt.event.ActionListener(){
publicvoidactionPerformed(ActionEvente){
cmdExit_actionPerformed(e);
}
}
this.addWindowListener(newjava.awt.event.WindowAdapter(){
publicvoidwindowClosing(WindowEvente){
this_windowClosing(e);
}
}

  上面程序分别为退出和窗体注册事件的侦听器或适配器,它们处理各自的交互动作。实现cmdExit_actionPerformed()和this_windowClosing()方法如下:

voidcmdExit_actionPerformed(ActionEvente){
System.exit(0);
}
voidthis_windowClosing(WindowEvente){
System.exit(0);
}

  3.SmtpMail类的实现

  采用Open()方法,建立与邮件服务器之间的TCP/IP连接,创建套接字,并且得到发送命令所用的输出流Send和接收服务器相应所用的输入流Rev。Open()方法的代码如下:

publicintopen(StringserverName,intport){
try{
mailSocket=newSocket(serverName,port);
send=newPrintWriter(mailSocket.getOutputStream(),true);
recv=newBufferedReader(newInputStreamReader(mailSocket.getInputStream()));
Strings1=recv.readLine();
charc=s1.charAt(0);
if((c=='4')|(c=='5'))
return0;
}
catch(Exceptione){
return0;
}
return1;
}

  在SmtpMail类中,通过Transmit()方法完成发送任务。Transmit()方法的代码如下:

publicinttransmit(){
booleanflag=true;
//发送HELO命令
if(domain.length()!=0){
inti=sendString("HELO"+domain);
if(i!=1)
return0;
}
//发送MAILFROM命令(发件人)
if(from.length()!=0){
intj=sendString("MAILFROM:"+from);
if(j!=1)
return0;
}
//发送RCPTTO命令(收件人)
if(to.length()!=0){
intk=sendString("RCPTTO:"+to);
if(k!=1)
return0;
}
//发送邮件正文(DATA命令)
if(sendString("DATA")!=1)
return0;
//发送邮件头信息
for(intl=0;l<x_set.size();l+=2){
Strings=(String)x_set.elementAt(l);
send.println(s+":"+x_set.elementAt(l+1));
}
//发送时间及相关内容格式说明
if(x_set.indexOf("Date")<0)
send.println("Date:"+(newDate()).toString());

  使用SendString()方法来发送字符串命令,并且接收邮件服务器的响应信息,判断命令是否被接收。返回1表示命令被拒绝执行,返回0表示命令被接受。SendString()方法的代码如下:

责编:豆豆技术应用

正在加载评论...