我这里用的是1.2版本,将相关包(jar文件)加到classpath中
二:该程序非常简单,不需要我们考虑很多地层的东西,因为api都帮我们做好了这些事情,下面是一个简单的发邮件的servlet:(对于熟悉的人来说,恐怕是再简单不过了的一个servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import sun.net.smtp.*;
public class sendmailservlet extends httpservlet {
public static string mail_from = "from";
public static string mail_to = "to";
public static string mail_subject = "subject";
public static string mail_body = "body";
public static string mail_host = "mailhost";
public void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception
{
resp.setcontenttype("text/html; charset=gb2312");
printwriter out = resp.getwriter();
out.println("<form method=post action=\"" + req.getrequesturi() + "\">");
out.println("<table>");
out.println("<tr><td>send mail server:</td>");
out.println("<td><input type=text name=" + mail_host + " size=30></td></tr>");
out.println("<tr><td>from:</td>");
out.println("<td><input type=text name=" + mail_from + " size=30></td></tr>");
out.println("<tr><td>to:</td>");
out.println("<td><input type=text name=" + mail_to + " size=30></td></tr>");
out.println("<tr><td>subject:</td>");
out.println("<td><input type=text name=" + mail_subject + " size=30></td></tr>");
out.println("<tr><td>text:</td>");
out.println("<td><textarea name=" + mail_body + " cols=40 rows=10></textarea></td></tr>");
out.println("</table><br>");
out.println("<input type=submit value=\"send\">");
out.println("<input type=reset value=\"reset\">");
out.println("</form>");
out.flush();
}
public void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception,ioexception
{
resp.setcontenttype("text/html; charset=gb2312");
printwriter out = new printwriter(resp.getoutputstream());
string from = req.getparameter(mail_from);
string to = req.getparameter(mail_to);
string subject = req.getparameter(mail_subject);
string body = req.getparameter(mail_body);
string mailhost = req.getparameter(mail_host);
try
{
smtpclient mailer = new smtpclient(mailhost);
mailer.from(from);
mailer.to(to);
printstream ps = mailer.startmessage();
ps.println("from: " + from);
ps.println("to: " + to);
ps.println("subject: " + subject);
ps.println(body);
mailer.closeserver();
out.println("success!");
}
catch (exception ex)
{
out.println("an error about:" + ex.getmessage());
}
out.flush();
}
public void init(servletconfig cfg) throws servletexception
{
super.init(cfg);
}
public void destroy()
{
super.destroy();
}
}