javamail是基于SMTP协议和POP3协议的邮件发送与接收系统,在用户注册与登陆的过程中,常需要用到邮箱验证功能,下面是基于javamail的一个简单实现
用户注册后通过servlet得到邮箱地址,并使用方法发送邮件
//校验用户名
if(dao.findUserByName(user.getUsername())!=null)
{
throw new RuntimeException("用户名已经存在")
}
//调用DAO中的方法添加用户
user.setRole("user")
user.setState(0)
user.setActivecode(UUID.randomUUID().toString())
dao.addUser(user)
//发送激活邮件
Properties prop = new Properties()
prop.setProperty("mail.transport.protocol", "smtp")
prop.setProperty("mail.smtp.host", "localhost")
prop.setProperty("mail.smtp.auth", "true")
prop.setProperty("mail.debug", "true")
Session session=Session.getInstance(prop)
Message msg=new MimeMessage(session)
msg.setFrom(new InternetAddress("aa@zj.com"))
msg.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail()))
msg.setSubject(user.getUsername()+",来自estore的激活邮件")
msg.setText(user.getUsername()+"点击如下链接激活用户,如果不能点击请复制到浏览器地址栏访问:localhost/Estore/ActiveServlet?activecode="+user.getActivecode())
Transport trans=session.getTransport()
trans.connect("aa","123")
trans.sendMessage(msg, msg.getAllRecipients())
//conn.commit()
}catch(Exception e)
{
e.printStackTrace()
throw new RuntimeException(e)
}
}
链接地址代码
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserService service=BasicFactory.getFactory().getService(UserService.class);
String activecode=request.getParameter("activecode");
User user=service.active(activecode);
request.getSession().setAttribute("user", user);
response.getWriter().write("激活成功,3秒回主页");
response.setHeader("Refresh", "3;url=index.jsp");
}
与数据库中的激活码进行验证
public User active(String activecode) {
User findU=new User();
findU.setActivecode(activecode);
User user=dao.findUserByActivecode(activecode);
if(user==null)
{
throw new RuntimeException("激活码不存在,请检查您的激活码");
}
if(user.getState()!=0)
{
throw new RuntimeException("用户已经激活,不要重复激活,请直接登陆");
}
if(System.currentTimeMillis() - user.getUpdatetime().getTime()>1000*3600*24)
{
dao.delete(user.getId());
throw new RuntimeException("激活码超时,此用户作废,请重新注册");
}
dao.updateState(user.getId());
user.setState(1);
return user;
}
完成