SpringBoot实现发送QQ邮箱验证码
打开qq邮箱官网
点击设置
找到开启服务:POP3/SMTP
然后复制给的密授权码(记住)
导入maven依赖坐标
<!--qq邮箱--><!-- /artifact/org.springframework.boot/spring-boot-starter-mail --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId><version>2.2.6.RELEASE</version></dependency>
创建一个Controller类
@RestController@RequestMapping("/email")public class EmailController {@Resourceprivate JavaMailSender javaMailSender;//读取yml文件中username的值并赋值给form@Value("${spring.mail.username}")private String from;@RequestMapping("sendEmail")public String sendSimpleMail(@RequestParam(value = "emailReceiver") String emailReceiver) {// 构建一个邮件对象SimpleMailMessage message = new SimpleMailMessage();// 设置邮件发送者message.setFrom(from);// 设置邮件接收者message.setTo(emailReceiver);// 设置邮件的主题message.setSubject("登录验证码");// 设置邮件的正文Random random = new Random();StringBuilder code = new StringBuilder();for (int i = 0; i < 6; i++) {int r = random.nextInt(10);code.append(r);}String text = "您的验证码为:" + code + ",请勿泄露给他人。";message.setText(text);// 发送邮件try {javaMailSender.send(message);return "发送成功";} catch (MailException e) {e.printStackTrace();}return "发送失败";}}
配置文件:
server:port: 8080spring:application:name: QQEmaildatasource:druid:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: rootpassword: "20020630"mail:# 配置 SMTP 服务器地址host: # 发送者邮箱username: 1978500345@# 配置密码,注意不是真正的密码,而是刚刚申请到的授权码password: gdfdlmbkclducgaj# 端口号465或587port: 587# 默认的邮件编码为UTF-8default-encoding: UTF-8# 配置SSL 加密工厂properties:mail:smtp:socketFactoryClass: .ssl.SSLSocketFactory#表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
发送的url格式为http://localhost:8080/email/sendEmail?emailReceiver=1978500345@
后面加的是要发送的q