该案例包含三个文件,分别为上传文件页面sendMail.jsp,上传文件处理类SendMailServlet.java,显示结果页面sendResult.jsp。
<form id="form1" name="form1" method="post" action="<%=request.getContextPath()%>/servlet/sendMail"> <table width="516" height="253" border="0" align="center"> <tr> <td>收件人:</td> <td><label> <input type="text" name="to" id="to" /> </label></td> </tr> <tr> <td>发件人:</td> <td><label> <input type="text" name="from" id="from" /> </label></td> </tr> <tr> <td>主题:</td> <td><label> <input type="text" name="subject" id="subject" /> </label></td> </tr> <tr> <td>内容:</td> <td><label> <textarea name="content" id="content" cols="45" rows="8"></textarea> </label></td> </tr> <tr> <td><label> <input type="submit" name="button" id="button" value="提交" /> </label></td> <td><label> <input type="reset" name="button2" id="button2" value="重置" /> </label></td> </tr> </table> </form>
web.xml中添加servlet处理
<servlet> <servlet-name>sendMailServlet</servlet-name> <servlet-class>com.email.SendMailServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>sendMailServlet</servlet-name> <url-pattern>/servlet/sendMail</url-pattern> </servlet-mapping>
在servlet类SendMailServlet.java中处理邮件发送
public class SendMailServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); //处理请求页面中文字符集 request.setCharacterEncoding("gbk"); response.setContentType("text/html; charset=gbk"); //简单的邮件处理 SimpleEmail email = new SimpleEmail(); //设置邮件发送的服务器 email.setHostName("smtp.163.com"); //邮件发送验证用户名,密码 email.setAuthentication("emailtest_001", "123456"); //设置邮件接收字符集 email.setCharset("gbk"); try { //设置邮件信息,发送人,接受人,主题,内容等信息,信息内容从请求页面中得到 email.setFrom(request.getParameter("from")); email.addTo(request.getParameter("to")); email.setSubject(request.getParameter("subject")); email.setMsg(request.getParameter("content")); //发送邮件 email.send(); request.setAttribute("sendmail.message", "邮件发送成功!"); } catch (EmailException e) { // TODO Auto-generated catch block e.printStackTrace(); request.setAttribute("sendmail.message", "邮件发送不成功!"); } //请求转发到结果页面 request.getRequestDispatcher("/sendResult.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
SimpleEmail类处理简单的邮件发送,必须经过网易服务器的验证,即必须通过
email.setHostName("smtp.163.com");
email.setAuthentication("emailtest_001", "123456");
设置验证信息。如要更改服务器信息只需更改服务器域名HostName,但是用户名,密码必须是该服务器下的注册的用户!!