public void connect() throws SMTPException{
try{
smtp = new Socket(smtpServer,port);
input = new BufferedReader(new InputStreamReader(smtp.getInputStream()));
output = new PrintStream(smtp.getOutputStream());
serverReply = input.readLine();
if(serverReply.charAt(0)=='2' || serverReply.charAt(0)=='3'){
}
else{
throw new SMTPException("Error connecting to SMTP server "
+ smtpServer + "on port " + port);
}
}catch(Exception e){
throw new SMTPException(e.getMessage());
}
}
public void hail(String mailfrom,String mailto) throws SMTPException{
if(submitCommand("HELLO" + smtpServer))
throw new SMTPException("Error ocurred during HELLO command.");
if(submitCommand("MAIL FROM:" + mailfrom))
throw new SMTPException("Error during MAIL command");
if(submitCommand("RCPT TO:" + mailto))
throw new SMTPException("Error during RCPT command");
}
public void sendMessage(String mailfrom,String mailto,String subject,String message)
throws SMTPException{
Date ldate_today = new Date(System.currentTimeMillis());
SimpleDateFormat lgmt_date = new SimpleDateFormat("d MMM YYYY HH:MM:SS 'GMT'");
lgmt_date.setTimeZone(TimeZone.getTimeZone("GMT"));
lgmt_date.format(ldate_today);
if(submitCommand("DATA")){
throw new SMTPException("Error during DATA command");
}
String header = "From:" + mailfrom + "\r\n";
header += "To:" + mailto + "\r\n";
header += "Subject:" + subject + "\r\n";
header += "Date:" + lgmt_date +"\r\n\r\n";
if(submitCommand(header + message + "\r\n"))
throw new SMTPException("Eror during mail transmission.");
}
public String getServerReply(){
return serverReply;
}
public int getPort(){
return port;
}
public void setPort(int newPort){
port = newPort;
}
public String getSmtpServer(){
return smtpServer;
}
public void setSmtpServer(String newSmtpServer){
smtpServer = newSmtpServer;
}
public void logout() throws SMTPException{
try{
if(submitCommand("QUIT"))
throw new SMTPException("Error during QUIT command");
input.close();
output.flush();
output.close();
smtp.close();
}catch(Exception e){
}
}
}
//Java Bean中引用的类的文件
package mailer;
//For a comprehensive tutorial as well as the current SMTP protocal
//go to http://www.jspinsider.com/tutorial/insider.html.
public class SMTPException extends Exception{
private String message;
public SMTPException(String message){
this.message = message;
}