SpringBoot整合邮件发送
1、导入maven坐标
<!--邮件发送-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、编写yaml配置
spring:
mail:
default-encoding: UTF-8
host: smtp.qq.com
password: dpfbdheg #SMTP的密码,并不是自己的登录密码,具体获取下面给出(这里以QQ邮箱为例)
port: 587
properties:
mail:
debug: true
protocol: smtp
smtp:
socketFactory: javax.net.ssl.SSLSocketFactory
username: 2059468666@qq.com #自己的电子邮箱
具体实现
@RestController
@RequestMapping("/send")
@Slf4j
public class TestEmailController {
@Value("${spring.mail.username}")
private String from;
@Resource
private JavaMailSender javaMailSender;
@RequestMapping("/email")
public void sendEmailCode(String email,String code, Integer type){
try {
Date date = new Date();
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); //发送人
message.setTo(email); //向谁发送验证码
message.setSentDate(date); //发送时间
if (type == 1){
message.setSubject("【邮箱注册校验】"); //发送标题
message.setText("您本次注册邮箱帐号的验证码是:" + code + ",有效期为5分钟,请在5分钟内完成注册");
}
if (type == 2){
message.setSubject("【邮箱忘记密码校验】"); //发送标题
message.setText("您本次修改邮箱帐号密码的验证码是:" + code + ",有效期为5分钟,请在5分钟内完成注册");
}
javaMailSender.send(message);
} catch (MailException e) {
log.error("邮箱发送失败",e);
}
}
}
测试:
效果: