`
2277259257
  • 浏览: 497497 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

发送邮箱验证---金猫实例

 
阅读更多

/**
     * 发送激活邮件
     * @param map
     * @param request
     * @param response
     * @param status
     * @throws NumberFormatException
     * @throws Exception
     */
    @RequestMapping("/center/processbind")
    public void processbind(ModelMap map,HttpServletRequest request, HttpServletResponse response, SessionStatus status) throws NumberFormatException, Exception{
        //取出用户信息
        User user = this.getCurrUser(request, response);
        Long userId = user.getId();
        Map<String, String> params = getParamMap(request);
        Map<String, Object> tips = new HashMap<String, Object>();
        String email = params.get("email");
        //判断邮箱是否为空
        if(!StringUtil.isEmpty(email)) {
            //正则表达式验证邮箱格式
            String regex = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(email);
            if(!matcher.matches()) {
                tips.put("status", 1);
                tips.put("info", "邮箱格式不正确");
                tips.put("data", "");
            } else {

                //验证邮箱是否已存在
                User getByEmail = userService.getByEmail(email);
                if(getByEmail != null) {
                    tips.put("status", 1);
                    tips.put("info", "该邮箱已绑定");
                    tips.put("data", "");
                } else {
                    //生成发送激活邮箱的时间戳
                    Date date = new Date();
                    Long addtime = date.getTime()/1000;
                    //生成邮箱验证激活码
                    Random rand = new Random();
                    int ran = rand.nextInt(100);
                    String validateCode = userId+email+addtime+ran;
                    MD5 md5 = new MD5();
                    String hash = md5.getMD5ofStr(validateCode);

                    //保存邮箱信息到xf_bind_email表,用于验证
                    Object savebindemail = bindEmailService.savebindemail(userId, hash, addtime, email);
                    if(savebindemail != null) {
                        //邮箱绑定处理类(如下)
                        BindEmailAction bindEmailAction = new BindEmailAction();
                        //激活邮箱发送
                        bindEmailAction.processbind(email, hash);
                        //截取邮箱,拼接为邮箱官网
                        String suffix = "mail."+email.substring(email.lastIndexOf("@")+1);
                        tips.put("status", 0);
                        tips.put("info", "我们已向您的邮箱发送了一封验证邮件");
                        tips.put("data", suffix);
                    }
                }
            }
        } else {
                tips.put("status", 1);
                tips.put("info", "邮箱为空");
                tips.put("data", "");
        }
        this.out(response, tips);
    }

 

 

public class BindEmailAction {
 
 /**
  * 处理激活
  * @param email
  * @param hash
  */
 public void processbind(String email,String hash) {
  //邮件的内容
        StringBuffer buffer=new StringBuffer("点击下面链接激活账号,48小时生效,否则重新注册账号,链接只能使用一次,请尽快激活!</br>");
        buffer.append("<a href=\"http://localhost:8080/jinrongmao/center/bind.html?email=");激活码请求
        buffer.append(email);
        buffer.append("&validateCode=");
        buffer.append(hash);
        buffer.append("\">http://localhost:8080/jinrongmao/center/bind.html?email=");
        buffer.append(email);
        buffer.append("&validateCode=");
        buffer.append(hash);
        buffer.append("</a>");
        //设置邮件
  MailSenderInfo mailInfo = new MailSenderInfo();
  mailInfo.setMailServerHost("smtp.ym.163.com");//SMTP服务器
  mailInfo.setMailServerPort("25");//端口
  mailInfo.setValidate(true);//设置是否验证身份
  mailInfo.setUserName("postmaster@jinrongmao360.com");//服务器邮箱
  mailInfo.setPassword("jinrongmao?360+");//服务器邮箱密码
  mailInfo.setFromAddress("postmaster@jinrongmao360.com");//发送人邮箱
  mailInfo.setToAddress(email);//收信人邮箱
  mailInfo.setSubject("激活邮箱");//设置邮箱标题
  mailInfo.setContent(buffer.toString());//设置邮箱内容
     //邮件发送类
        SimpleMailSender mailSender = new SimpleMailSender();
        mailSender.sendHtmlMail(mailInfo);//发送HTML格式邮件
 }
}

 

 

 

/** 
* 简单邮件(不带附件的邮件)发送器 
*/  
public class SimpleMailSender  {           
    /** 
      * 以HTML格式发送邮件 
      * @param mailInfo 待发送的邮件信息 
      */  
    public static boolean sendHtmlMail(MailSenderInfo mailInfo){  
      // 判断是否需要身份认证  
      MyAuthenticator authenticator = null; 
      Properties pro = mailInfo.getProperties(); 
      //如果需要身份认证,则创建一个密码验证器   
      if (mailInfo.isValidate()) {  
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); 
      }  
      // 根据邮件会话属性和密码验证器构造一个发送邮件的session  
      Session sendMailSession = Session.getDefaultInstance(pro,authenticator);  
      try {  
      // 根据session创建一个邮件消息  
      Message mailMessage = new MimeMessage(sendMailSession);  
      // 创建邮件发送者地址  
      Address from = new InternetAddress(mailInfo.getFromAddress());  
      // 设置邮件消息的发送者  
      mailMessage.setFrom(from);  
      // 创建邮件的接收者地址,并设置到邮件消息中  
      Address to = new InternetAddress(mailInfo.getToAddress());  
      // Message.RecipientType.TO属性表示接收者的类型为TO  
      mailMessage.setRecipient(Message.RecipientType.TO,to);  
      // 设置邮件消息的主题  
      mailMessage.setSubject(mailInfo.getSubject());  
      // 设置邮件消息发送的时间  
      mailMessage.setSentDate(new Date());  
      // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象  
      Multipart mainPart = new MimeMultipart();  
      // 创建一个包含HTML内容的MimeBodyPart  
      BodyPart html = new MimeBodyPart();  
      // 设置HTML内容  
      html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");  
      mainPart.addBodyPart(html);  
      // 将MiniMultipart对象设置为邮件内容  
      mailMessage.setContent(mainPart);  
      // 发送邮件  
      Transport.send(mailMessage);  
      return true;  
      } catch (MessagingException ex) {  
          ex.printStackTrace();  
      }  
      return false;  
    }  
}  

 

邮件信息封装类

public class MailSenderInfo {  
    // 发送邮件的服务器的IP和端口  
    private String mailServerHost;  
    private String mailServerPort;  
    // 邮件发送者的地址  
    private String fromAddress;  
    // 邮件接收者的地址  
    private String toAddress;  
    // 登陆邮件发送服务器的用户名和密码  
    private String userName;  
    private String password;  
    // 是否需要身份验证  
    private boolean validate;  
    // 邮件主题  
    private String subject;  
    // 邮件的文本内容  
    private String content;  
    // 邮件附件的文件名  
    private String[] attachFileNames;    
    /** 
      * 获得邮件会话属性 
      */  
    public Properties getProperties(){  
      Properties p = new Properties();  
      p.put("mail.smtp.host", this.mailServerHost);  
      p.put("mail.smtp.port", this.mailServerPort);  
      p.put("mail.smtp.auth", validate ? "true" : "false");  
      return p;  
    }  
}

 

密码验证器类

public class MyAuthenticator extends Authenticator{ 
    String userName=null; 
    String password=null; 
      
    public MyAuthenticator(){ 
    } 
    public MyAuthenticator(String username, String password) {  
        this.userName = username;  
        this.password = password;  
    }  
    protected PasswordAuthentication getPasswordAuthentication(){ 
        return new PasswordAuthentication(userName, password); 
    } 
}

 

 

 /**
     * 验证激活码
     * @param map
     * @param request
     * @param response
     * @param status
     * @return
     * @throws NumberFormatException
     * @throws Exception
     */
    @RequestMapping("/center/bind")
    public String bind(ModelMap map,HttpServletRequest request, HttpServletResponse response, SessionStatus status) throws NumberFormatException, Exception{
     //取出用户信息
     User user = this.getCurrUser(request, response);
     Long userId = user.getId();
     BindEmail bindEmail = bindEmailService.getByUserId(userId);
     Map<String, String> params = getParamMap(request);
     String hash = params.get("validateCode");
     String email = params.get("email");
     String succMsg = "";
     String errorMsg = "";
     //验证邮箱地址是否正确
     if(email.equals(bindEmail.getEmail())) {
                Date currentTime = new Date();//获取当前时间 
                //验证链接是否过期
                currentTime.before(new Date(bindEmail.getAddtime()*1000L));
                if(currentTime.before(bindEmail.getLastActivateTime())) { 
                    //验证激活码是否正确
                    if(hash.equals(bindEmail.getHash())) {

                     //保存邮箱到xf_user表(用于更改流程状态)
                     int changeEmail = userService.changeEmail(userId, email);
                     if(changeEmail>0) {
                      //激活或修改成功,并把邮箱绑定
                         succMsg = "绑定成功";
                            map.addAttribute("succMsg",succMsg);
                            map.addAttribute("email",email);
                         return "/center/bind_email_success";
                     } else {
                      //激活或修改失败
                      errorMsg = "系统繁忙,请下次再试";
                            map.addAttribute("errorMsg",errorMsg);
                         return "/center/bind_email";
                     }
                    } else { 
                       errorMsg = "激活码不正确";
                       map.addAttribute("errorMsg",errorMsg);
                       return "/center/bind_email";
                    } 
                } else {
                  errorMsg = "激活码已过期";
                     map.addAttribute("errorMsg",errorMsg);
                     return "/center/bind_email";
                } 
        } else {
            errorMsg = "邮箱地址不正确";
            map.addAttribute("errorMsg",errorMsg);
            return "/center/bind_email";
        } 
    }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics