这里使用的是QQ邮箱,其他邮箱类似。
1.获取授权码
进入QQ邮箱主页面,找到左上方设置 , 选择账户选项卡,往下拉看到
把第一项POP3/SMTP服务开启,然后按照他的步骤获取授权码,并且记录下来。
2.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.配置配置文件
#邮件发送配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
#邮箱号
spring.mail.username=输入你的邮箱号
#授权码
spring.mail.password=输入刚刚获得的授权码
#邮件发送安全配置
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
其他不用改
4.编写服务类
@Service
public class MailService{
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender mailSender;
Logger logger = LoggerFactory.getLogger(this.getClass());
public void sendVertifyCode(String to, String title, String content){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); //发送人
message.setTo(to); //收件人
message.setSubject(title); //邮件名
message.setText(content); //邮件内容(验证码)
mailSender.send(message);
logger.info("已经发送");
}
}
5.编写测试类
直接在springboot自带的test文件下的启动类下编写就好了。
@RunWith(SpringRunner.class)
@SpringBootTest(classes= DemoApplication.class) //这里DemoApplication要改成你的项目启动类名
class DemoApplicationTests {
@Autowired
private MailService mailService;
@Test
void contextLoads() {
}
@Test
void Test1(){
/*填你的测试信息*/
String to =
String title=
String context =
mailService.sendVertifyCode(to,title,context);
}
}
6.结果
控制台打印了日志信息
然后去邮箱里看看有没有收到邮件,注意可能会在垃圾箱里哦!