JAVA/JSP学习系列之JavaMail发邮件

ZDNet软件频道 时间:2008-06-28 作者: | 中国IT实验室 我要评论()
本文关键词:JavaMail Java JSP
该程序非常简单,不需要我们考虑很多地层的东西,因为API都帮我们做好了这些事情,下面是一个简单的发邮件的Servlet:(对于熟悉的人来说,恐怕是再简单不过了的一个servlet).
一:条件 必须下载sun公司的JavaMail API包,地址为:http://java.sun.com/products/javamail/
  
  我这里用的是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("
  ");
  
  out.println(" ");
  
  out.println("
   send mail server: ");
  
  out.println("
   
  ");
  
  out.println("
   from: ");
  
  out.println("
   
  ");
  
  out.println("
   to: ");
  
  out.println("
   
  ");
  
  out.println("
   subject: ");
  
  out.println("
   
  ");
  
  out.println("
   text: ");
  
  out.println("
   
  ");
  
  out.println("
  
  ");
  
  out.println("");
  
  out.println("");
  
  out.println("
  ");
  
  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
  
  
  
  public void destroy()
  
  {
  
  super.destroy();
  
  }
  
  }

百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134