回复人: sharetop(天生很笨) (2001-6-21 16:36:00)  得90分 /**
发送Email 的JavaBean@author sharetop
@version 1.0.1
created date:2001-4-25采用直接写Socket方式发送email
关于SMTP(SIMPLE MAIL TRANSFER PROTOCOL)命令,
参考 http://www.faqs.org/rfcs/rfc821.html*/import java.io.*;
import java.util.*;
import java.net.*;public class Email
{
  private static final String CONTENT_TYPE = "text/html";  private String smtpServer=null;
  private String fromMail=null;
  private String toMail=null;
  
  public Email(String smtp,String from,String to)
  {
  this.smtpServer=smtp;
  this.fromMail=from;
  this.toMail=to;
  }
  
  public void mail(String subject,String content) throws MailException
  {    try{
  
  //打开邮件服务器port:25
  Socket s = new Socket(smtpServer,25);
  
  //用于socket读写数据
  PrintWriter out = new PrintWriter(s.getOutputStream(),true); 
  BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    
    String res = null; //smtp服务器返回信息    out.println("HELO "+smtpServer);
res=in.readLine();
if( !res.startsWith("220") ) throw new MailException("MailException:"+res);    out.println("MAIL FROM: "+fromMail);
    res = in.readLine();
    if( !res.startsWith("250") ) throw new MailException("MailException:"+res);  out.println("RCPT TO: "+toMail);
    res = in.readLine();
    if( !res.startsWith("250") ) throw new MailException("MailException:"+res);    out.println("DATA");
    res = in.readLine();
    if( !res.startsWith("250") ) throw new MailException("MailException:"+res);
    
    out.println("Subject:"+subject);
    out.println("From:"+fromMail);
    out.println("To:"+toMail);
    out.println("Content-Type: text/html; charset=gb2312");
    out.println(content);    out.println(".");
    res = in.readLine();
if( !res.startsWith("354") ) throw new MailException("MailException:"+res);
    
out.println("QUIT");
    s.close();
  }
  catch(UnknownHostException x) {
  throw new MailException("MailException:"+x.getMessage());
  }
  catch(IOException x){
  throw new MailException("MailException:"+x.getMessage());
  }
}//end method mail}//end class Email//发送邮件违例类
class MailException extends Exception
{
public MailException(String msg)
{
super(msg);
}
}