600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Spring Boot使用qq邮箱实现验证码发送

Spring Boot使用qq邮箱实现验证码发送

时间:2021-07-12 08:03:20

相关推荐

Spring Boot使用qq邮箱实现验证码发送

1、获取授权码

登录qq邮箱,点击【设置】——》》【账户】

下滑至下图所示位置,点击开启,按要求发送短信验证码

!!!

记录图中的授权码,下面一步会用到

2、配置yml文件

spring:mail:# 配置 SMTP 服务器地址host: # 发送者邮箱username: xxxxxxxxx@# 配置密码,注意不是真正的密码,而是刚刚申请到的授权码password: **********# 端口号465或587port: 587# 默认的邮件编码为UTF-8default-encoding: UTF-8# 配置SSL 加密工厂properties:mail:smtp:socketFactoryClass: .ssl.SSLSocketFactory#表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误debug: true

3、添加并刷新maven依赖

<!--qq邮箱--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>

4、编写controller层

import org.springframework.beans.factory.annotation.Value;import org.springframework.mail.MailException;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.Random;@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 "发送失败";}}

测试效果如下

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。