- 整合mail依赖。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
然后将自己的邮箱打开客户端服务。
-
以qq邮箱为例,前往设置->账号。开启pop3或者imap服务即可,保存授权码后面用到。
-
-
配置application.yml。
spring: profiles: active: dev mail: #邮件作者名 username: mahuateng@qq.com password: 授权码 host: smtp.qq.com properties: mail: smtp: ssl: enable: true #发邮件邮箱 mail: fromMail: addr: mahuateng@qq.com
-
写一个测试类测试代码运行结果。
package com.shengxi.resys; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ResysApplicationTests { @Autowired JavaMailSender mailSender; //邮件发件人 @Value("${mail.fromMail.addr}") private String from; @Test public void testMail() { String emailServiceCode = "1234"; SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("修改密码验证码"); message.setText("注册验证码是:" + emailServiceCode); message.setFrom(from); message.setTo("wangyizhu@163.com"); mailSender.send(message); } }
运行成功,登录收邮件邮箱查看结果即可。