Spring框架提供了一种使用JavaMailSender接口发送电子邮件的简单抽象方法,而Spring Boot为其提供了自动配置以及启动程序模块。
1.准备工作
1.1 开启第三方登录邮箱
以qq邮箱为例:
进入邮箱设置----------帐户页面,并打开以下全部服务
1.2 引入依赖
在pom.xml文件中添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
也可在新建项目时直接勾选以下依赖:
2.配置MailSender
我们需要作出以下必要配置,否则无法发送邮件:
- 配置邮箱用户名:
填写自己的邮箱账号 - 配置邮箱密码
填写授权码(此授权码有效期直至你下次修改密码)
- 配置邮箱服务器
qq邮箱是smtp.qq.com - 使能ssl连接
此外,还需要设置超时参数,因为某些默认超时值是无限的,可能需要更改此值,以避免线程被无响应的邮件服务器阻塞。
配置如下:
spring:
mail:
username: xxxx@qq.com
password: xxxxx
host: smtp.qq.com
properties:
smtp.ssl.enable: true
mail.smtp.connectiontimeout