小工具知识网

当前位置: 首页 > 行业知识 > 【SpringBoot】| 邮箱发送验证码,你会了吗?

行业知识

【SpringBoot】| 邮箱发送验证码,你会了吗?

2026-12-06 11:27:17 来源:互联网转载

目录

  • 题外话
  • 提前准备
    • 2.1 配置邮箱第三方登录
      • 2.1.1 点击设置——账户
      • 2.1.2 开启POP3/SMTP服务
      • 2.2 添加依赖
      • 2.3 yaml配置
      • 进入主题
      • 测试使用
      • 尾声
        • 3.1 安利一个生成验证码的工具类
          • 3.1.1 添加依赖
          • 3.1.2 编写配置类
          • 3.1.3 使用
          • 3.1.4 演示结果
          • 3.2 再见

            题外话

            日常生活中,咱们注册某一个平台或者找回密码甚至是登录到系统的时候,一般都需要注册手机号,经过手机号来接收验证码,然后完成这些需求。但是对于程序员来说,或许我们更加感兴趣的是如何来实现它,但是一般这种经过三大运营商的操作,都是需要付费的,所以咱们今天来讲一种它的平替——使用QQ邮箱来发送和接收验证码。qq邮箱是咱们日常使用到的既方便又免费的通讯工具之一(方便是因为日常使用微信,一般会和QQ邮箱关联)。现在咱们来介绍一下它在SpringBoot项目中的具体应用。

            提前准备

            2.1 配置邮箱第三方登录

            在系统中使用到的邮箱发送邮件属于第三方登录,需要登录QQ邮箱配置第三方登录。

            2.1.1 点击设置——账户

            1. 登录QQ邮箱,点击设置,跳转后找到账户。

            2.1.2 开启POP3/SMTP服务

            在账户那个页面,找到下面这一栏,点击开始就好啦。

            然后会让你绑定邮箱的手机验证一下:

            发送完信息,就会显示下面的授权码(一定要保存好,很重要),复制授权码备用。

            2.2 添加依赖

            回到项目,添加相关依赖,如下:

              org.springframework.boot  spring-boot-starter-mail

            tips:

            Spring提供了非常好用的JavaMailSender接口实现邮件发送。由于SpringBoot的Starter模块也为此提供了自动化配置,所以在引入了spring-boot-starter-mail依赖之后,会根据配置文件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使用的地方直接@Autowired来引入邮件发送对象。

            2.3 yaml配置

            在这里配置好自己的邮箱和授权码,当然这里是自定义的,后面需要使用**@Value**获取。

            # 发送邮件配置mail:  # 发件人地址  user: 23734xxxxxx@qq.com  # 发件人授权码  password: pfemtwstpvkdabcd

            进入主题

            完成前面的步骤后,我们正式写一个发送邮件的工具类(建议直接复制)。

            import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.util.Properties;/** * 发邮件工具类 */@Componentpublic final class MailUtils {    @Value("${mail.user}")    private String USER; // 发件人邮箱地址    @Value("${mail.password}")    private String PASSWORD; // 如果是qq邮箱可以使户端授权码    /**     * 发送邮件     * @param to 收件人邮箱     * @param text 邮件正文     * @param title 标题     */    public boolean sendMail(String to, String text, String title){        try {            final Properties props = new Properties();            props.put("mail.smtp.auth", "true");            props.put("mail.smtp.host", "smtp.qq.com");            // 发件人的账号            props.put("mail.user", USER);            //发件人的密码            props.put("mail.password", PASSWORD);            // 构建授权信息,用于进行SMTP进行身份验证            Authenticator authenticator = new Authenticator() {                @Override                protected PasswordAuthentication getPasswordAuthentication() {                    // 用户名、密码                    String userName = props.getProperty("mail.user");                    String password = props.getProperty("mail.password");                    return new PasswordAuthentication(userName, password);                }            };            // 使用环境属性和授权信息,创建邮件会话            Session mailSession = Session.getInstance(props, authenticator);            // 创建邮件消息            MimeMessage message = new MimeMessage(mailSession);            // 设置发件人            String username = props.getProperty("mail.user");            InternetAddress form = new InternetAddress(username);            message.setFrom(form);            // 设置收件人            InternetAddress toAddress = new InternetAddress(to);            message.setRecipient(Message.RecipientType.TO, toAddress);            // 设置邮件标题            message.setSubject(title);            // 设置邮件的内容体            message.setContent(text, "text/html;charset=UTF-8");            // 发送邮件            Transport.send(message);            return true;        }catch (Exception e){            e.printStackTrace();        }        return false;    }}

            这个工具类使用了**@Component**注解将这个工具类放入IOC容器中,需要使用的时候方便取。这个工具类只有一个方法——sendMail(String to, String text, String title),就是用来发邮件的方法,一共三个参数,参数解释如上有很详细的解释,这里就不多言。

            测试使用

            现在我们使用它来测试一下好不好使。

            1.

            2.

            尾声

            3.1 安利一个生成验证码的工具类

            3.1.1 添加依赖

            com.github.pengglekaptcha2.3.2

            3.1.2 编写配置类

            验证码的形式可以在下面改,这里是生成四位数字+字母的形式。

            import com.google.code.kaptcha.Producer;import com.google.code.kaptcha.impl.DefaultKaptcha;import com.google.code.kaptcha.util.Config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.Properties;/** * 生成验证码的配置 */@Configurationpublic class KaptchaConfig {    @Bean    public Producer kaptchaProducer() {        Properties properties = new Properties();        //设置验证码的宽度        properties.setProperty("kaptcha.image.width", "100");        //设置宽度        properties.setProperty("kaptcha.image.height", "40");        //设置字体大小        properties.setProperty("kaptcha.textproducer.font.size", "32");        //设置字体颜色        properties.setProperty("kaptcha.textproducer.font.color", "0,0,0");        //限定验证码中的字符        properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");        //设置验证码的长度        properties.setProperty("kaptcha.textproducer.char.length", "4");        //设置添加噪声与否        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");        //将配置装载到一个实例中        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();        //将配置传入实例        defaultKaptcha.setConfig(new Config(properties));        return defaultKaptcha;    }}

            3.1.3 使用

            @Autowiredprivate Producer checkCode;@Testvoid contextLoads() {String text = checkCode.createText();System.out.println(true);}

            3.1.4 演示结果

            3.2 再见

            好了,今天的分享结束,咱们下期见。

上一篇:掌握购票秘籍,轻松搞定12306购票攻略!

下一篇:苹果应用商店软件下载收费机制解析