邮箱发送邮件
前置条件:在springboot中使用邮箱发送邮件
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
设置配置文件(application.yml)
spring:
mail:
# smtp服务主机 qq邮箱则为smtp.qq.com 163邮箱是smtp.163.com
host: smtp.qq.com
# 发送邮件的账户
username: [email protected]
# 授权码
password: xxxxxxxxxx
default-encoding: UTF-8
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
test-connection: true
生成验证码的工具类
代码:
import java.security.SecureRandom;
import java.util.Random;
/**
* @Classname VerCodeGenerateUtil
* @Description 生成验证码工具类
* @Date 2021/9/7 14:23
* @Created by DB
*/
public class VerCodeGenerateUtil {
//验证码包含的字段,可自己设置
private static final String SYMBOLS = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
private static final Random RANDOM = new SecureRandom();
// 生成 6 位数的随机数字
public static String generateVerCode() {
// 如果是六位,就生成大小为 6 的数组
char[] numbers = new char[6];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(numbers);
}
}
实体类
代码:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ToEmail implements Serializable {
// 邮件接收方,这是一个数组,所以可以一次性发送给多个用户
private String[] tos;
// 邮件主题
private String subject;
// 邮件内容
private String content;
}
Controller层
代码:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* TODO 邮箱验证码
*
*/
@RestController
@RequestMapping("/email")
@Slf4j
public class EmailController {
// 引入邮件接口
@Autowired
private JavaMailSender mailSender;
// 获得发件人信息
@Value("${spring.mail.username}")
private String username;
/**
*
* @param toEmail 需要发送的对象
* @return
*/
@GetMapping("/sendEmail")
public R<String> commonEmail(ToEmail toEmail) {
log.info("现在进入到发送验证码了");
// 创建邮件消息
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(username);
message.setTo(toEmail.getTos());
String verCode = VerCodeGenerateUtil.generateVerCode();
message.setSubject("您本次的验证码是:"+verCode);
message.setText("尊敬的用户,您好:\n"
+ "\n本次请求的邮件验证码为:" + verCode + ",本验证码 5 分钟内效,请及时输入。(请勿泄露此验证码)\n"
+ "\n如非本人操作,请忽略该邮件。\n(这是一封通过自动发送的邮件,请不要直接回复)");
mailSender.send(message);
return R.success("发送成功");
}
}
Postman测试
测试是成功的,有正确收到验证码
标签:String,org,验证码,springframework,发送,import,邮箱,邮件 From: https://www.cnblogs.com/itchen-2002/p/17434173.html