springboot实现邮箱验证码功能

springboot实现邮箱验证码功能

本文实例为大家分享了springboot实现邮箱验证码功能的具体代码,供大家参考,具体内容如下:
以我的qq为例

第一步:开通qq POP3/SMTP服务和IMAP/SMTP服务

*加粗样式
在这里插入图片描述

第二步:导入maven依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

第三步:properties文件配置文件

#邮件发送配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=你的qq邮箱
spring.mail.password=你的qq授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

第四步 编写MsmServiceImpl

package com.lzb.msmservice.service.impl;

import com.lzb.msmservice.service.MsmService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String username;

    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public boolean sent(String email, String title, String code) {

        if(StringUtils.isEmpty(email)) return false;
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo(email);
        message.setSubject(title);
        message.setText(code);
        mailSender.send(message);
        logger.info("邮件发送成功");
        return true;
    }
}

第五步 编写MsmController

package com.lzb.msmservice.controller;
import com.lzb.commonutils.R;
import com.lzb.msmservice.service.MsmService;
import com.lzb.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @GetMapping("/sentEmail/{email}")
    public R sentEmail(@PathVariable String email){
        String code = redisTemplate.opsForValue().get(email);
        if(!StringUtils.isEmpty(code)) return R.ok();
        code = RandomUtil.getFourBitRandom();
        boolean  flag = msmService.sent(email, "注册验证码", code);
        if(flag){
            redisTemplate.opsForValue().set(email,code,1, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }

    }
}

第六步 编写验证码的生成文件

package com.atguigu.msmservice.util;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 获取随机数
 * 
 * @author qianyi
 *
 */
public class RandomUtil {

	private static final Random random = new Random();

	private static final DecimalFormat fourdf = new DecimalFormat("0000");

	private static final DecimalFormat sixdf = new DecimalFormat("000000");

	public static String getFourBitRandom() {
		return fourdf.format(random.nextInt(10000));
	}

	public static String getSixBitRandom() {
		return sixdf.format(random.nextInt(1000000));
	}

	/**
	 * 给定数组,抽取n个数据
	 * @param list
	 * @param n
	 * @return
	 */
	public static ArrayList getRandom(List list, int n) {

		Random random = new Random();

		HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

		// 生成随机数字并存入HashMap
		for (int i = 0; i < list.size(); i++) {

			int number = random.nextInt(100) + 1;

			hashMap.put(number, i);
		}

		// 从HashMap导入数组
		Object[] robjs = hashMap.values().toArray();

		ArrayList r = new ArrayList();

		// 遍历数组并打印数据
		for (int i = 0; i < n; i++) {
			r.add(list.get((int) robjs[i]));
			System.out.print(list.get((int) robjs[i]) + "\t");
		}
		System.out.print("\n");
		return r;
	}
}

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中集成邮箱验证码功能,你可以按照以下步骤进行操作: 1. 在项目的pom.xml文件中添加mail模块的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 这样就可以使用Spring Boot提供的邮件功能了。\[1\] 2. 在配置文件(application.properties或application.yml)中填写相关的邮箱配置,例如使用163邮箱: ```properties # Mail spring.mail.host=smtp.163.com spring.mail.username=your-email@163.com spring.mail.password=your-password spring.mail.default-encoding=UTF-8 mail.from=your-email@163.com ``` 其中,`spring.mail.host`是SMTP服务器地址,`spring.mail.username`和`mail.from`是你的邮箱地址,`spring.mail.password`是你的邮箱授权码(不是邮箱密码)。你需要在相关邮箱设置中开启SMTP服务,并获取授权码。\[2\]\[3\] 3. 在你的代码中使用JavaMailSender发送邮件,可以通过注入`JavaMailSender`对象来实现: ```java @Autowired private JavaMailSender javaMailSender; public void sendVerificationCode(String email, String code) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(email); message.setSubject("验证码"); message.setText("您的验证码是:" + code); javaMailSender.send(message); } ``` 以上代码示例中,`sendVerificationCode`方法用于发送验证码邮件,其中`email`是收件人邮箱地址,`code`是验证码内容。你可以根据实际需求自定义邮件的主题和内容。 这样,你就可以在Spring Boot中集成邮箱验证码功能了。记得替换相关配置为你自己的邮箱信息。 #### 引用[.reference_title] - *1* *2* *3* [Spring Boot 整合163或者qq邮箱发送验证码](https://blog.csdn.net/hghjgkjn/article/details/125952509)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值