基于SpringBoot实现邮件发送
chenlong
发布:2021-09-30 13:49:44阅读:
(1)首先看邮箱配置部分,配置获取163邮箱授权码,配置完以后会获取一个16位的授权码,后面会作为密码,详见后文(QQ的自行网上参考)


(2)导入Spring邮件依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
(3)基于yml配置相关配置,注:密码非邮箱密码,而是步骤1中获取到的授权码
spring: mail: #smtp服务主机 qq邮箱则为smtp.qq.com host: smtp.163.com #服务协议 protocol: smtp # 编码集 default-encoding: UTF-8 #发送邮件的账户 username: 177xxxxxxxx@163.com #授权码(步骤1中获取的16位的授权码) password: xxxxxxxxxxxxxxxx test-connection: true properties: mail: smtp: auth: true starttls: enable: true required: true
(4)在Controller里面添加接口方法
@Autowired
private JavaMailSenderImpl mailSender;
@Value("${spring.mail.username}")
private String from;
@RequestMapping(value = "/sendSimpleMail", method = RequestMethod.POST)
@ResponseBody
public JsonResult<String> sendSimpleMail(@RequestBody ToEmail toEmail) {
//创建简单邮件消息
SimpleMailMessage message = new SimpleMailMessage();
//谁发的
message.setFrom(from);
//谁要接收
message.setTo(toEmail.getTos());
//邮件标题
message.setSubject(toEmail.getSubject());
//邮件内容
message.setText(toEmail.getContent());
try {
mailSender.send(message);
return JsonResult.success( "发送普通邮件成功");
} catch (MailException e) {
e.printStackTrace();
return JsonResult.failWithMsg("普通邮件方失败");
}
}(5)最后调用接口测试,邮件发送成功,查看邮件正常发送

小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧