Java 发送邮件
- 在pom.xml文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 在 application.yml 文件中添加配置参数:
spring:
mail:
username: 1905138802@qq.com
password: yjxthmzszuycdgie
host: smtp.qq.com
default-encoding: utf-8
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
port: 587
username:自己的邮箱账号,我用的是QQ邮箱
password:生成的授权码,可参考链接:https://jingyan.baidu.com/article/5552ef479c6354518ffbc9dd.html
host:smtp.qq.com(这是QQ邮箱的)
por:我使用的是587,用465不成功,可参考链接:https://blog.csdn.net/qq_38695490/article/details/103775299
3. 在接口中定义发送邮件的方法
public interface EmailService {
void send();
}
4.在接口实现类中实现该方法
@Autowired
private EmailMapper emailMapper;
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
@Override
public void send() {
// Email email = emailMapper.selectById(emailId);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo("h657055130@163.com");
message.setSubject("email.getTheme()");
message.setText("这是来自视频管理平台报警设置的邮件");
mailSender.send(message);
}
JavaMailSender是spring boot集成,可直接用
5.在controller中调用此方法
@TokenParam
@ApiOperation(response = Email.class, value = "J-1 发送邮件")
@PostMapping("/send")
public Res sendEmail(){
emailService.send();
return Res.ok("返回成功");
}
6.邮件发送成功
文章参考链接:
https://blog.csdn.net/qq_38695490/article/details/103775299
https://www.jianshu.com/p/a7097a21b42d
https://jingyan.baidu.com/article/5552ef479c6354518ffbc9dd.html
感谢以上链接作者!
若有错误,请批评指正。