这篇文章简单的模拟了网上利用邮箱激活用户注册这样的一个功能 1. 呈现给用户的注册界面:(为了简单起见,就剩下两个输入域,邮箱和昵称)
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>用户注册利用邮箱进行验证</title>
- </head>
- <body>
- <br/>
- <form action="${pageContext.request.contextPath }/servlet/RegisterServlet" method="post">
- <font size="24" color="red">用户注册</font><br/>
- 邮箱:<input type="text" name="email" /><br/>
- 昵称:<input type="text" name="userName" /><br/>
- <input type="submit" value="submit" /><br/>
- </form>
- </body>
- </html>
2. 用户点击提交后,应该在后台进行发送邮件的处理,在这之前,你可能需要利用JavaScript对邮箱进行匹配处理,以及对用户大部分的输入情况进行验证,如果有验证码的话,应该首先验证(可以通过AJAX进行验证)。但是我在这里也就不验证了,直接假设用户输入是正确的。下面是后台处理程序:
- package com.piedra.register;
- import java.io.IOException;
- import java.util.Date;
- import java.util.Properties;
- import javax.mail.Address;
- import javax.mail.Authenticator;
- import javax.mail.Message.RecipientType;
- import javax.mail.MessagingException;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import com.piedra.model.MyAuthenticator;
- public class RegisterServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String toMail = request.getParameter("email");
- String registerName = request.getParameter("userName");
- String userName = "你邮箱地址";
- String password = "你邮箱密码";
- String registerId = "" + Math.random() * Math.random();
- String url = "http://localhost:8080/JavaMailChecker/servlet/MailBackServlet?registerId=" + registerId;//待会用户点在邮箱中点击这个链接回到你的网站。
- HttpSession httpSession = request.getSession();
- httpSession.setAttribute(registerId, registerName);
- httpSession.setMaxInactiveInterval(600);
- Properties props = new Properties();
- props.setProperty("mail.smtp.host", "smtp.163.com");
- props.setProperty("mail.smtp.auth", "true");
- Authenticator authenticator = new MyAuthenticator(userName, password);
- javax.mail.Session session = javax.mail.Session.getDefaultInstance(props,authenticator);
- session.setDebug(true);
- try{
- Address from = new InternetAddress(userName);
- Address to = new InternetAddress(toMail);
- MimeMessage msg = new MimeMessage(session);
- msg.setFrom(from);
- msg.setSubject("诚实网站注册");
- msg.setSentDate(new Date());
- msg.setContent("<a href="' + url + '">点击" + url + "完成注册</a>", "text/html;charset=utf-8");
- msg.setRecipient(RecipientType.TO, to);
- /*
- Transport transport = session.getTransport("smtp");
- transport.connect("smtp.163.com", userName, password);
- transport.sendMessage(msg,msg.getAllRecipients());
- transport.close();
- */
- Transport.send(msg);
- } catch(MessagingException e){
- e.printStackTrace();
- }
- request.getRequestDispatcher("/sendMailSuccess.jsp").forward(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
这段代码中需要的Authenticator 代码如下:
- package com.piedra.model;
- import javax.mail.Authenticator;
- import javax.mail.PasswordAuthentication;
- public class MyAuthenticator extends Authenticator {
- private String userName;
- private String password;
- public MyAuthenticator(String userName, String password){
- this.userName = userName;
- this.password = password;
- }
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(userName, password);
- }
- }
3. 使用上面的代码也就可以把你需要用户点击的链接成功的发送到他的邮箱了,但是你还需要一个处理用户点击链接后的操作,在这些操作中你需要真正完成用户的注册。
- package com.piedra.register;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class MailBackServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String registerID = request.getParameter("registerId");
- if(registerID == null){
- request.getRequestDispatcher("/index.jsp").forward(request,response);
- return ;
- }
- String registerName = (String)request.getSession().getAttribute(registerID);
- if(registerName == null || registerName.equals("")){
- request.getRequestDispatcher("/index.jsp").forward(request,response);
- return ;
- }
- request.setAttribute("registerName", registerName);
- request.getRequestDispatcher("/registSuccess.jsp").forward(request,response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- }
邮箱验证通过后,便跳转到注册成功的页面,在实际应用可能是要让用户跳转到自己网站的首页。
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>注册成功</title>
- </head>
- <body>
- 恭喜您,从现在起,您就是本站的一员了。<br/>
- 下面是您的昵称:<br/>
- ${registerName }
- </body>
- </html>
测试截图:
需要说明的问题:
1). 这个项目使用MyEclipse开发的,javaMail的jar包是1.4.4 。
2). 代码中注释掉的部分是另一种连接方式。
3). 尽管MyEclipse在开发javamail应用的时候已经为我们提供了mail.jar,但是我们还是需要将我们下载的javamail下lib目录下的jar包加到WEB-INF/lib目录下,不然会报错。
4). 如果你不是用163邮箱做实验,那么你需要查看你使用的邮箱的官方网站的帮助文档,这样你就能够获得smtp服务器的名称了,当然,你也可以选择google或者百度。
5). 严重声明,本人并未实际开发过这样的应用,这些仅供参考。
6). 在实验期间,你肯能会遇到一些问题,但是如果遇到 553 这样的问题,那么你可能需要下面的帮助
使用163 邮箱发送javamail邮件时的错误提示及原因
(1)553 Requested action not taken: Local user only SMTP类型的机器只允许发信人是本站用户;
用户名或密码不正确,并且需要设置如下属性
props.put("mail.smtp.auth", "true");
(2)553 Mail from must equal authorized user
发信人地址必须是当前登录邮箱的认证用户地址
例如,认证时使用的用户名为:abc
那么:String from = abc@163.com;
message.setFrom(new InternetAddress(from));