查看: 1531|回复: 0

[Java学习] Java APP移动端邮箱认证

发表于 2018-2-4 10:14:43
Java APP移动端邮箱认证

图片描述

前言:

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

一、邮箱服务的搭建。

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

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

  1. <!-- 邮箱服务依赖包 -->
  2. <dependency>
  3. <groupId>javax.mail</groupId>
  4. <artifactId>javax.mail-api</artifactId>
  5. <version>1.6.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.sun.mail</groupId>
  9. <artifactId>javax.mail</artifactId>
  10. <version>1.6.0</version>
  11. </dependency>
复制代码

2.如果是web工程,在lib包添加jar文件。网盘地址:链接:链接描述 密码:1lfu

二、邮件发送工具类

SMTP的host主要有万网、163、126、阿里云,分别为:

  1. 万网 smtp.mxhichina.com
  2. 163 smtp.163.com
  3. 126 smtp.126.com
  4. 阿里云 smtp.aliyun.com
复制代码
  1. /**
  2. *
  3. * Copyright ? 2017 Xunxin Network Technology Co. Ltd.
  4. *
  5. * @Author Noseparte
  6. * @Compile 2018年1月19日 -- 下午1:38:46
  7. * @Version 1.0
  8. * @Description 邮件工具类
  9. */
  10. public class SendEmail {
  11. // public static final String HOST = "smtp.aliyun.com"; //普通邮箱
  12. public static final String HOST = "smtp.qiye.aliyun.com"; //企业邮箱
  13. public static final String PROTOCOL = "smtp"; //协议类型
  14. public static final int PORT = 25; //端口号
  15. public static final int TIMELIMIT = 1000*60*60*24; //激活邮件过期时间24小时
  16. public static final String FROM = "***********"; //发件人的email
  17. public static final String PWD = "**********"; //发件人密码
  18. /**
  19. * 获取Session
  20. * @return
  21. */
  22. private static Session getSession() {
  23. Properties props = new Properties();
  24. props.put("mail.smtp.host", HOST);//设置服务器地址
  25. props.put("mail.store.protocol" , PROTOCOL);//设置协议
  26. props.put("mail.smtp.port", PORT);//设置端口
  27. props.put("mail.smtp.auth" , true);
  28. Authenticator authenticator = new Authenticator() {
  29. @Override
  30. protected PasswordAuthentication getPasswordAuthentication() {
  31. return new PasswordAuthentication(FROM, PWD);
  32. }
  33. };
  34. Session session = Session.getDefaultInstance(props , authenticator);
  35. return session;
  36. }
  37. public static void send(String toEmail , String content) {
  38. Session session = getSession();
  39. try {
  40. System.out.println("--send--"+content);
  41. // Instantiate a message
  42. Message msg = new MimeMessage(session);
  43. //Set message attributes
  44. msg.setFrom(new InternetAddress(FROM));
  45. InternetAddress[] address = {new InternetAddress(toEmail)};
  46. msg.setRecipients(Message.RecipientType.TO, address);
  47. msg.setSubject("******邮箱认证"); //邮件标题
  48. msg.setSentDate(new Date());
  49. msg.setContent(content , "text/html;charset=utf-8");
  50. //Send the message
  51. Transport.send(msg);
  52. }
  53. catch (MessagingException mex) {
  54. mex.printStackTrace();
  55. }
  56. }
  57. }
复制代码

三、邮件发送的API

  1. /**
  2. * 发送认证邮件
  3. *
  4. * @param phone
  5. * @param verifyCode
  6. * @return
  7. */
  8. @RequestMapping(value=Router.Personal.MAIL_AUTHENTICATION,method=RequestMethod.POST)
  9. @ResponseBody
  10. public Response mail_authentication(@RequestParam("userId") int userId,@RequestParam("email") String email,
  11. @RequestParam("authType") String authType) {
  12. log.info("InfoMsg:--- 发送认证邮件开始");
  13. Response response = this.getReponse();
  14. PageData pd = new PageData<>();
  15. try {
  16. PageData authPd = new PageData<>();
  17. pd.put("userId", userId);
  18. pd.put("authType", "cert");
  19. if(!userAuthenticationService.isAuthentication(authPd)) {
  20. return response.failure("请先进行实名认证");
  21. }
  22. UserEntity user = appUserService.findById(userId);
  23. String ID = user.getID();
  24. String name = user.getName();
  25. pd.put("id", userId);
  26. pd.put("email", email);
  27. String text = JSON.toJSONString(pd);
  28. String URL = "http://www.xunxinkeji.cn/app-api/personal";;
  29. String token = SymmetricEncoder.AESEncode(KEY_STR,text.toString());
  30. String content = "<p>亲爱的"+name+",您好。<br><br>您于:"+ PeriodsUtil.getWholeTime(new Date()) +"通过帐号:"+ID+"申请了循心APP的邮箱认证,请点击如下链接完成认证."
  31. +"<br><a href='"+URL+"/activate_mail/?token="+token+"&email="+email+"'>"
  32. +URL+"/activate_mail/?token="+token+"&email="+email+"</a><br><br>(如果您无法点击此链接,请将其复制到浏览器地址栏后访问)<br>为了保障您帐号的安全性,请在24小时内完成认证,此链接将在认证后失效!</p>";
  33. SendEmail.send(email, content);
  34. UserAuthentication auth = new UserAuthentication(email, "mail", 1, "", "", new Date(), userId);
  35. userAuthenticationService.save(auth);
  36. log.info("InfoMsg:--- 发送认证邮件结束");
  37. return response.success();
  38. } catch (Exception e) {
  39. log.error("errorMsg:--- 发送认证邮件失败:" + e.getMessage());
  40. return response.failure(e.getMessage());
  41. }
  42. }
复制代码

四、邮箱认证的回调通知

  1. /**
  2. * 邮箱认证异步通知
  3. *
  4. * @param phone
  5. * @param verifyCode
  6. * @return
  7. */
  8. @RequestMapping(value=Router.Personal.ACTIVATE_MAIL,method=RequestMethod.GET)
  9. @ResponseBody
  10. public ModelAndView activate_mail(@RequestParam("email") String email,@RequestParam("token") String token) {
  11. log.info("InfoMsg:--- 邮箱激活认证开始");
  12. ModelAndView mv = this.getModelAndView();
  13. PageData pd = new PageData<>();
  14. String msg = "";
  15. try {
  16. if(StringUtils.trim(token).equals("") && StringUtils.isBlank(token)) {
  17. return new ModelAndView("/error");
  18. }
  19. String jsonObj = SymmetricEncoder.AESDncode(KEY_STR,token);
  20. JSONObject obj = JSON.parseObject(jsonObj);
  21. int userId = Integer.parseInt(obj.getString("id"));
  22. UserEntity user = appUserService.findById(userId);
  23. UserAuthentication auth = userAuthenticationService.model(userId, "mail");
  24. if(null != auth) {
  25. if((PeriodsUtil.addDate(auth.getAuthTime()) + 1000*60*60*24) < PeriodsUtil.addDate(new Date())) {
  26. msg = "亲爱的用户,很抱歉,您的认证信息已超过有效期!";
  27. }else {
  28. msg = "亲爱的用户,恭喜您认证成功。";
  29. appUserService.setEmail(userId,email);
  30. PageData emailPd = new PageData<>();
  31. emailPd.put("userId", userId);
  32. emailPd.put("authType", "mail");
  33. emailPd.put("authState", 2);
  34. String authRemark = user.getNickName() + "于:" + PeriodsUtil.getWholeTime(new Date()) + "进行了实名认证.";
  35. emailPd.put("authRemark", authRemark);
  36. emailPd.put("authTime", new Date());
  37. userAuthenticationService.update(emailPd);
  38. //认证动态记录
  39. UserDynamicRecordVO vo = new UserDynamicRecordVO(0, "", "我新增了邮箱认证。", DynamicConstants.AUTHENT_CHANGE, "", userId, 0);
  40. userDynamicRecordService.save(vo);
  41. //赠送积分
  42. int userExp = user.getUserExp();
  43. appUserService.user_exp_change(userId, userExp + 50);
  44. //生成积分记录
  45. UserExpChangeRecord record = new UserExpChangeRecord(ExpConstants.AUTHENTICATION, ExpConstants.INCOME, userExp, 50, userExp+50, userId);
  46. userExpChangeRecordService.save(record);
  47. }
  48. }
  49. pd.put("msg", msg);
  50. mv.addObject("pd", pd);
  51. mv.setViewName("jsp/platform/notice");
  52. log.info("InfoMsg:--- 邮箱激活认证结束");
  53. return mv;
  54. } catch (Exception e) {
  55. log.error("errorMsg:--- 邮箱激活认证失败:" + e.getMessage() + "---}");
  56. return new ModelAndView("/error");
  57. }
  58. }
复制代码


回复

使用道具 举报