当前位置:   article > 正文

邮箱发送验证码以及验证码的验证_绑定安全邮箱请输入邮箱获取验证码完成邮件可能会有延时,请耐心等待,如果长时间

绑定安全邮箱请输入邮箱获取验证码完成邮件可能会有延时,请耐心等待,如果长时间

1.本篇文章的代码原理是根据前端传来的用户名到数据库中取对应的邮箱,并通过邮箱帮助类向邮箱发送验证码,将验证码存在session中,最后通过前端传过来的验证码与存在session中的验证码进行比较,如果相同则进行下一步(用户注册时的邮箱验证或者后面面的忘记密码)。

2.调试后台API用的是Swagger

3.用到的依赖:

  1. <!-- javaMail -->
  2. <dependency>
  3. <groupId>javax.mail</groupId>
  4. <artifactId>mail</artifactId>
  5. <version>1.4.6</version>
  6. </dependency>

1.帮助类(即放到utils包下的类) 

1.1EmailConfig

  1. public class EmailConfig {
  2. //发送邮件的方法
  3. public static void sendEmail(String toEmailAddress, String emailTitle, String emailContent) throws Exception {
  4. //读取配置文件中的配置信息
  5. String emailSMTPHost = PropertiesConfig.getEmailKey("emailSMTPHost");
  6. String emailSMTPPort = PropertiesConfig.getEmailKey("emailSMTPPort");
  7. String emailAccount = PropertiesConfig.getEmailKey("emailAccount");
  8. String emailPassword = PropertiesConfig.getEmailKey("emailPassword");
  9. Properties pros = new Properties();
  10. //采用debug调试
  11. pros.setProperty("mail.debug", "true");
  12. //身份验证
  13. pros.setProperty("mail.smtp.auth", "true");
  14. //邮箱端口号,QQ一般为456或者587
  15. pros.put("mail.smtp.port", emailSMTPPort);
  16. //设置邮件服务器的主机名,就是那个服务器地址
  17. pros.setProperty("mail.smtp.host", emailSMTPHost);
  18. //选择发送邮件的协议
  19. pros.setProperty("mail.transport.protocol", "smtp");
  20. //SSL认证,这个主要看邮箱是否基于SSL加密,加密的话需要开启才可以使用
  21. MailSSLSocketFactory sf = new MailSSLSocketFactory();
  22. sf.setTrustAllHosts(true);
  23. //这边需要设置是否使用SSL安全连接
  24. pros.put("mail.smtp.ssl.enable", "true");
  25. pros.put("mail.smtp.ssl.socketFactory", sf);
  26. //创建一个session回话
  27. Session session = Session.getInstance(pros);
  28. //获取邮件信息
  29. Message msg = new MimeMessage(session);
  30. //设置邮件标题
  31. msg.setSubject(emailTitle);
  32. //设置内容
  33. StringBuilder builder = new StringBuilder();
  34. //写入内容
  35. builder.append("\n" + emailContent);
  36. //设置邮件内容
  37. //msg.setText(builder.toString());
  38. msg.setContent(builder.toString(), "text/html;charset=gb2312");
  39. //设置显示邮件发送时间
  40. msg.setSentDate(new Date());
  41. //设置发件人邮箱,这里的InternetAddress有三个参数:发件人邮箱,显示的昵称(需要改成自己的),昵称字符集
  42. msg.setFrom(new InternetAddress(emailAccount, "发送人的昵称", "utf-8"));
  43. /现在我们要获取一个邮差了,不然没人传递邮件了
  44. Transport transport = session.getTransport();
  45. //连接自己的邮箱
  46. transport.connect(emailSMTPHost, emailAccount, emailPassword);
  47. //发送邮件
  48. transport.sendMessage(msg, new Address[]{new InternetAddress(toEmailAddress)});
  49. transport.close();
  50. }
  51. }

1.2 PropertiesConfig

  1. Component
  2. public class PropertiesConfig implements ApplicationListener {
  3. //保存加载配置参数
  4. private static Map<String, String> aliPropertiesMap = new HashMap<String, String>();
  5. //保存邮件配置参数
  6. private static Map<String, String> emailPropertiesMap = new HashMap<>();
  7. /*获取配置参数值*/
  8. public static String getKey(String key) {
  9. return aliPropertiesMap.get(key);
  10. }
  11. /*获取邮件配置参数值*/
  12. public static String getEmailKey(String key) {
  13. return emailPropertiesMap.get(key);
  14. }
  15. /*监听启动完成,执行配置加载到aliPropertiesMap*/
  16. public void onApplicationEvent(ApplicationEvent event) {
  17. if (event instanceof ApplicationReadyEvent) {
  18. this.init(aliPropertiesMap);//应用启动加载
  19. this.initEmail(emailPropertiesMap);
  20. }
  21. }
  22. /*初始化加载aliPropertiesMap*/
  23. public void init(Map<String, String> map) {
  24. // 获得PathMatchingResourcePatternResolver对象
  25. PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  26. try {
  27. //加载resource文件(也可以加载resources)
  28. Resource resources = resolver.getResource("classpath:config/alipay.properties");
  29. PropertiesFactoryBean config = new PropertiesFactoryBean();
  30. config.setLocation(resources);
  31. config.afterPropertiesSet();
  32. Properties prop = config.getObject();
  33. //循环遍历所有得键值对并且存入集合
  34. for (String key : prop.stringPropertyNames()) {
  35. map.put(key, (String) prop.get(key));
  36. }
  37. } catch (Exception e) {
  38. new Exception("配置文件加载失败");
  39. }
  40. }
  41. /*初始化加载aliPropertiesMap*/
  42. public void initEmail(Map<String, String> map) {
  43. // 获得PathMatchingResourcePatternResolver对象
  44. PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  45. try {
  46. //加载resource文件(也可以加载resources)
  47. Resource resources = resolver.getResource("classpath:config/email.properties");
  48. PropertiesFactoryBean config = new PropertiesFactoryBean();
  49. config.setLocation(resources);
  50. config.afterPropertiesSet();
  51. Properties prop = config.getObject();
  52. //循环遍历所有得键值对并且存入集合
  53. for (String key : prop.stringPropertyNames()) {
  54. map.put(key, (String) prop.get(key));
  55. }
  56. } catch (Exception e) {
  57. new Exception("配置文件加载失败");
  58. }
  59. }
  60. /*读取配置文件,将数据放置map内*/
  61. public static Map<String, Double> getRateMap() {
  62. Map<String, Double> map = new HashMap<String, Double>();
  63. // 获得PathMatchingResourcePatternResolver对象
  64. PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  65. try {
  66. //加载resource文件(也可以加载resources)
  67. Resource resources = resolver.getResource("classpath:config/payPercent.properties");
  68. PropertiesFactoryBean config = new PropertiesFactoryBean();
  69. config.setLocation(resources);
  70. config.afterPropertiesSet();
  71. Properties prop = config.getObject();
  72. //循环遍历所有得键值对并且存入集合
  73. for (String key : prop.stringPropertyNames()) {
  74. map.put(key, Double.parseDouble((String) prop.get(key)));
  75. }
  76. } catch (Exception e) {
  77. new Exception("配置文件加载失败");
  78. }
  79. return map;
  80. }
  81. }

2.API接口(根据用户名查询邮箱并发送验证码以及邮箱验证码验证的具体实现) EmailController

  1. @RestController
  2. @RequestMapping("sendEmail")
  3. @Api(basePath = "sendEmail", value = "邮件发送", description = "邮件发送")
  4. public class EmailController {
  5. @Autowired
  6. private UserService userService;
  7. /**
  8. * 根据用户名查询邮箱并发送验证码
  9. *
  10. */
  11. @RequestMapping(method = RequestMethod.POST, value = "/sendVerifyEmail")
  12. @SysLog("根据用户名查询邮箱并发送验证码")
  13. @ApiOperation(value = "根据用户名查询邮箱并发送验证码", notes = "根据用户名查询邮箱并发送验证码", httpMethod = "POST")
  14. public R sendVerifyEmail(@RequestParam String username, HttpSession session) {
  15. try {
  16. //根据用户名查询邮箱
  17. UserNode frontUser=userService.findUserByUserName(username);
  18. if(Util.isEmpty(frontUser)){
  19. return R.error("该用户不存在");
  20. }else if(Util.isEmpty(frontUser.getEmail())){
  21. return R.error("未填写邮箱!");
  22. }else {
  23. String toEmailAddress = frontUser.getEmail();
  24. //生成验证码
  25. String verifyCode = VertifyCodeUtil.generateVertifyCode(6);
  26. //邮箱标题
  27. String emailTitle = "【xxx系统】邮箱验证";
  28. //邮件内容
  29. String emailContent = "您好,您生成的验证码为:" + verifyCode + ",请在十分钟内完成验证!";
  30. EmailConfig.sendEmail(toEmailAddress, emailTitle, emailContent);
  31. //将生成的验证码存入session,用作后续验证
  32. session.setAttribute("verifyCode", verifyCode);
  33. session.setAttribute("userId", frontUser.getId());
  34. return R.ok(toEmailAddress);
  35. }
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. return R.error("邮件发送失败");
  39. }
  40. }
  41. /**
  42. * 邮箱验证码验证
  43. *
  44. *
  45. */
  46. @RequestMapping(method = RequestMethod.POST, value = "/emailCodeVerify")
  47. @SysLog("邮箱验证码验证")
  48. @ApiOperation(value = "邮箱验证码验证", notes = "邮箱验证码验证", httpMethod = "POST")
  49. public R emailCodeVerify(String verifyCode,HttpSession session) {
  50. //从session中获取验证码
  51. // String code=(String)session.getAttribute("CODE_IN_SESSION");
  52. String code=(String)session.getAttribute("verifyCode");
  53. //TimerTask实现10分钟后删除CODE_IN_SESSION
  54. final Timer timer = new Timer();
  55. timer.schedule(new TimerTask() {
  56. @Override
  57. public void run() {
  58. //session.removeAttribute("CODE_IN_SESSION");
  59. session.removeAttribute("verifyCode");
  60. System.out.println("verifyCode删除成功");
  61. timer.cancel();
  62. }
  63. },10 * 60 * 1000);
  64. if (verifyCode==null){
  65. return R.error("验证码不能为空!");
  66. }
  67. //十分钟后提示验证码已过期
  68. if (code==null){
  69. return R.error("验证码已过期,请重新进行验证!");
  70. }
  71. if(Util.isNotEmpty(code)&&Util.isNotEmpty(verifyCode)&&code.equals(verifyCode)){
  72. //Integer userId=(Integer)session.getAttribute("userId");
  73. Long userId=(Long)session.getAttribute("userId");
  74. return R.ok(userId);
  75. }else{
  76. return R.error("验证码不正确!");
  77. }
  78. }
  79. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/196177
推荐阅读
相关标签
  

闽ICP备14008679号