导入依赖
org.springframework.boot
spring-boot-starter-mail
2.2.4.RELEASE
使用maven阿里云配置无法下载,需自行下载,实现看上篇文章
application.properties配置
spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.default-encoding=GBK
# 发送邮件的账户
spring.mail.username=xxxxx@qq.com
# 授权码 邮箱服务器提供的授权码,不是你邮箱的密码
spring.mail.password=
# 开启一些权限
spring.mail.test-connection=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
在QQ邮箱设置开启SMTP
发送邮件
package com.jcss.controller;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@RestController
@CrossOrigin //允许跨域访问
public class EmailController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
JavaMailSender javaMailSender; //可直接注入邮件发送的对象
@Value("${spring.mail.username}") //动态获取配置文件中 发送邮件的账户
private String sendemail;
@GetMapping("/getEmailCode")
public String getEmailCode(String email){
//随机生成一个四位数的验证码
int yzm = new Random().nextInt(9999) % (9999 - 1000 + 1) + 1000;
//创建简单邮件消息
SimpleMailMessage message = new SimpleMailMessage();
//谁发的
message.setFrom(sendemail);
//谁要接收
message.setTo(email);
//邮件标题
message.setSubject("欢迎你");
//邮件内容
message.setText("您的验证码是"+yzm);
javaMailSender.send(message);
redisTemplate.opsForValue().set("yzm:" + yzm, JSON.toJSONString(yzm), 1, TimeUnit.DAYS);
return "发送成功";
}
}
具体使用在登录,注册,还是修改密码看自己喜欢了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)