springboot实现邮箱发送验证码

学习目标:

上一篇文章用到了阿里云的短信服务这个服务是需要付费且个人用户不容易申请,还有没有其他能收到验证码并且免费的,然后我就想到了QQ邮箱接收信息,


准备工作:

  1. 设置在授权码(QQ邮箱->设置->账户 找到【POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务】,点击【生成授权码】)

开始编码:

第一步导入依赖

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

在yml文件配置

 #配置邮件消息
 spring:
   mail:
     host: smtp.qq.com   //指定用来发送Email的邮件服务名
     username:          //设置用户名(QQ邮箱全名)
     password:  		//生成授权码
     default-encoding: UTF-8

编写实现发送代码

package com.example.shiro.sys.controller;

import com.example.shiro.sys.common.Result.R;
import com.example.shiro.sys.service.MsgSendService;
import com.example.shiro.sys.utlis.RedisUtil;
import com.example.shiro.sys.utlis.smsSend.RandomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;

/**
 * @Author:szm
 * @Date: 2022/4/28
 */
@RestController
@RequestMapping("/sys/send")
@RequiredArgsConstructor
public class MsgSendController {
    private final JavaMailSender mailSender; //注入QQ发送邮件的bean
    /**
     * 给qq邮箱发送消息
     */
    @GetMapping("/qqMsgSend")
    public R qqMsgSend(String qq,String msg){
        try {
            MimeMessage mimeMessage = this.mailSender.createMimeMessage();
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setFrom("设置发件qq邮箱");//设置发件qq邮箱
            qq+="@qq.com";
            message.setTo(qq);	//设置收件人
            message.setSubject("验证码");	//设置标题
            message.setText(msg);  	//第二个参数true表示使用HTML语言来编写邮件
            this.mailSender.send(mimeMessage);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return R.ok();
    }
}

最后也是获取到了,我测试用的是swagger-ui
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值