Java APP移动端邮箱认证

Java APP移动端邮箱认证

Java APP移动端邮箱认证_第1张图片
前言:
             要实现邮箱认证服务,大致分为以下四个步骤:搭建邮箱服务、制作一个发送邮件的工具类、后台实现一个供APP调用的接口API、邮箱认证的通知回调,当然这其中还涉及到邮件内容的设计和一个HTML/jsp页面,用来向用户显示认证结果。


一、邮箱服务的搭建。

在这里不展示SMTP邮箱服务的搭建,只介绍后台如何使用搭建。

1.如果项目是maven工程,在pom.xml文件中添加如下依赖。


   javax.mail
   javax.mail-api
   1.6.0


   com.sun.mail
   javax.mail
   1.6.0



2.如果是web工程,在lib包添加jar文件。网盘地址: 链接: https://pan.baidu.com/s/1dGYV4nJ   密码:1lfu


二、邮件发送工具类

SMTP的host主要有万网、163、126、阿里云, 分别为:
    万网     smtp.mxhichina.com
    163       smtp.163.com
    126       smtp.126.com
    阿里云     smtp.aliyun.com
/**
 *
 * Copyright © 2017 Xunxin Network Technology Co. Ltd.
 *
 * @Author Noseparte
 * @Compile 2018年1月19日 -- 下午1:38:46
 * @Version 1.0
 * @Description         邮件工具类
 */
public class SendEmail { 
    
//   public static final String HOST = "smtp.aliyun.com";       //普通邮箱
   public static final String HOST = "smtp.qiye.aliyun.com";    //企业邮箱
   public static final String PROTOCOL = "smtp";                //协议类型
   public static final int PORT = 25;                           //端口号
   public static final int TIMELIMIT = 1000*60*60*24;           //激活邮件过期时间24小时
   public static final String FROM = "*********";        //发件人的email 
   public static final String PWD = "********";                //发件人密码 
  
   /**
    * 获取Session
    * @return
    */ 
   private static Session getSession() { 
       Properties props = new Properties(); 
       props.put("mail.smtp.host", HOST);//设置服务器地址 
       props.put("mail.store.protocol" , PROTOCOL);//设置协议 
       props.put("mail.smtp.port", PORT);//设置端口 
       props.put("mail.smtp.auth" , true); 
        
       Authenticator authenticator = new Authenticator() { 
 
           @Override 
           protected PasswordAuthentication getPasswordAuthentication() { 
               return new PasswordAuthentication(FROM, PWD); 
           } 
            
       }; 
       Session session = Session.getDefaultInstance(props , authenticator); 
        
       return session; 
   } 
    
   public static void send(String toEmail , String content) { 
       Session session = getSession(); 
       try { 
           System.out.println("--send--"+content); 
           // Instantiate a message 
           Message msg = new MimeMessage(session); 
 
           //Set message attributes 
           msg.setFrom(new InternetAddress(FROM)); 
           InternetAddress[] address = {new InternetAddress(toEmail)}; 
           msg.setRecipients(Message.RecipientType.TO, address); 
           msg.setSubject("******邮箱认证");         //邮件标题  
           msg.setSentDate(new Date()); 
           msg.setContent(content , "text/html;charset=utf-8"); 
 
           //Send the message 
           Transport.send(msg); 
       } 
       catch (MessagingException mex) { 
           mex.printStackTrace(); 
       } 
   } 
}







三、邮件发送的API

 /**
        * 发送认证邮件
        *
        * @param phone
        * @param verifyCode
        * @return
        */
       @RequestMapping(value=Router.Personal.MAIL_AUTHENTICATION,method=RequestMethod.POST)
       @ResponseBody
       public Response mail_authentication(@RequestParam("userId") int userId,@RequestParam("email") String email,
                    @RequestParam("authType") String authType) {
             log.info("InfoMsg:--- 发送认证邮件开始");
             Response response = this.getReponse();
             PageData pd = new PageData<>();
             try {
                    PageData authPd = new PageData<>();
                    pd.put("userId", userId);
                    pd.put("authType", "cert");
                    if(!userAuthenticationService.isAuthentication(authPd)) {
                           return response.failure("请先进行实名认证");
                    }
                 UserEntity user = appUserService.findById(userId);
                 String ID = user.getID();
                 String name = user.getName();
                 pd.put("id", userId);
                 pd.put("email", email);
                 String text = JSON.toJSONString(pd);
            String URL = "http://www.xunxinkeji.cn/app-api/personal";;
            String token = SymmetricEncoder.AESEncode(KEY_STR,text.toString());
            String content = "

亲爱的"+name+",您好。

您于:"+ PeriodsUtil.getWholeTime(new Date()) +"通过帐号:"+ID+"申请了循心APP的邮箱认证,请点击如下链接完成认证." +"
" +URL+"/activate_mail/?token="+token+"&email="+email+"

(如果您无法点击此链接,请将其复制到浏览器地址栏后访问)
为了保障您帐号的安全性,请在24小时内完成认证,此链接将在认证后失效!

"; SendEmail.send(email, content); UserAuthentication auth = new UserAuthentication(email, "mail", 1, "", "", new Date(), userId); userAuthenticationService.save(auth); log.info("InfoMsg:--- 发送认证邮件结束"); return response.success(); } catch (Exception e) { log.error("errorMsg:--- 发送认证邮件失败:" + e.getMessage()); return response.failure(e.getMessage()); } }




四、邮箱认证的回调通知      
/**
	 * 邮箱认证异步通知
	 * 
	 * @param phone
	 * @param verifyCode
	 * @return
	 */
	@RequestMapping(value=Router.Personal.ACTIVATE_MAIL,method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView activate_mail(@RequestParam("email") String email,@RequestParam("token") String token) {
	    log.info("InfoMsg:--- 邮箱激活认证开始");
	    ModelAndView mv = this.getModelAndView();
	    PageData pd = new PageData<>();
	    String msg = "";
	    try {
	        if(StringUtils.trim(token).equals("") && StringUtils.isBlank(token)) {
	            return new ModelAndView("/error");
	        }
	        String jsonObj = SymmetricEncoder.AESDncode(KEY_STR,token);
	        JSONObject obj = JSON.parseObject(jsonObj);
	        int userId = Integer.parseInt(obj.getString("id"));
	        UserEntity user = appUserService.findById(userId);
	        UserAuthentication auth = userAuthenticationService.model(userId, "mail");
	        if(null != auth) {
	            if((PeriodsUtil.addDate(auth.getAuthTime()) + 1000*60*60*24) < PeriodsUtil.addDate(new Date())) {
	                msg = "亲爱的用户,很抱歉,您的认证信息已超过有效期!";
	            }else {
	                msg = "亲爱的用户,恭喜您认证成功。";
	                appUserService.setEmail(userId,email);
	                PageData emailPd = new PageData<>();
	                emailPd.put("userId", userId);
	                emailPd.put("authType", "mail");
	                emailPd.put("authState", 2);
	                String authRemark = user.getNickName() + "于:" + PeriodsUtil.getWholeTime(new Date()) + "进行了实名认证.";
	                emailPd.put("authRemark", authRemark);
	                emailPd.put("authTime", new Date());
	                userAuthenticationService.update(emailPd);
	                //认证动态记录
                    UserDynamicRecordVO vo = new UserDynamicRecordVO(0, "", "我新增了邮箱认证。", DynamicConstants.AUTHENT_CHANGE, "", userId, 0);
                    userDynamicRecordService.save(vo);
        	        //赠送积分
                    int userExp = user.getUserExp();
                    appUserService.user_exp_change(userId, userExp + 50);
        	        //生成积分记录
                    UserExpChangeRecord record = new UserExpChangeRecord(ExpConstants.AUTHENTICATION, ExpConstants.INCOME, userExp, 50, userExp+50, userId);
                    userExpChangeRecordService.save(record);
	            }
	        }
	        pd.put("msg", msg);
	        mv.addObject("pd", pd);
	        mv.setViewName("jsp/platform/notice");
	        log.info("InfoMsg:--- 邮箱激活认证结束");
	        return mv;
	    } catch (Exception e) {
	        log.error("errorMsg:--- 邮箱激活认证失败:" + e.getMessage() + "---}");
	        return new ModelAndView("/error");
	    }
	}
	




About Me:

  • Github地址:https://github.com/noseparte 
  • Email:  [email protected]     有java与hadoop相关的技术问题,可以发私信与我交流。
  • NPM地址:  https://www.npmjs.com/~noseparte
  • WebSite: http://www.noseparte.com/   Copyright © 2017 noseparte



   

你可能感兴趣的:(Java)