首先,您需要打开电子邮件的第三方支持并获得授权代码
以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); } }
测试结果