首先需要开启邮箱第三方支持以及获取授权码
以QQ邮箱为例:
QQ邮箱设置——账户
开启POP3/SMTP服务——完成验证后获得授权码,保存授权码
1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.然后在项目的application.yml
spring:
mail:
username: 你的QQ邮箱
password: 你的授权码
host: smtp.qq.com
properties:
mail.smtp.ssl.enable: true
3.编写测试方法进行测试
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ShopsApplicationTests {
@Autowired
JavaMailSenderImpl mailSender;
@Test
public void contextLoads() throws MessagingException {
int count = 1;//默认发送一次
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
while (count-- != 0) {
String codeNum = "";
int[] code = new int[3];
Random random = new Random();
//自动生成验证码
for (int i = 0; i < 6; i++) {
int num = random.nextInt(10) + 48;
int uppercase = random.nextInt(26) + 65;
int lowercase = random.nextInt(26) + 97;
code[0] = num;
code[1] = uppercase;
code[2] = lowercase;
codeNum += (char) code[random.nextInt(3)];
}
//标题
helper.setSubject("您的验证码为:" + codeNum);
//内容
helper.setText("您好!,感谢支持小站。您的验证码为:" + "<h2>" + codeNum + "</h2>" + "千万不能告诉别人哦!", true);
//邮件接收者
helper.setTo("123456789@qq.com");
//邮件发送者,必须和配置文件里的一样,不然授权码匹配不上
helper.setFrom("987654321@qq.com");
mailSender.send(mimeMessage);
}
}
测试结果