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;
}
完成