引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
yml配置-这是阿里和qq邮箱的配置
spring:
mail:
protocol: smtp
# 配置 SMTP 服务器地址
host: smtp.aliyun.com #阿里云
# host: smtp.qq.com #QQ
# 发送者邮箱
username: xxx@aliyun.com #阿里云邮箱
# username: xxx@qq.com #QQ邮箱
# 配置密码
#这里是授权码,阿里邮箱直接用密码即可
password: xxx #阿里云直接用密码
# password: xxx #QQ需要用授权码
# 端口号465或587
#port: 465
# 默认的邮件编码为UTF-8
default-encoding: UTF-8
# 配置SSL 加密工厂
properties:
mail:
smtp:
host: smtp.aliyun.com #阿里云
# host: smtp.qq.com #QQ
port: 465
auth: true
socketFactory:
class: javax.net.ssl.SSLSocketFactory
fallback: false
port: 465
#表示开启 DEBUG 模式,这样,邮件发送过程的日志会在控制台打印出来,方便排查错误
debug: true
这是网易邮箱的yml配置
spring:
mail:
host: smtp.163.com
#登陆账号
username: 网易邮箱账号
password: 授权码
default-encoding: UTF-8
#开启加密验证
properties:
mail:
smtp:
ssl:
enable: true
#以下项不用改动
starttls:
enable: true
required: true
网易企业邮箱免费版的没有授权码,收费的可能有,所以这里的授权码不是企业版的,获取授权码如下网易邮箱链接:
服务类
//定义邮件发送器
@Autowired
private JavaMailSender mailSender;
public void send() {
//创建一个简单文本邮件的对象
SimpleMailMessage message = new SimpleMailMessage();
//目标邮箱
message.setTo("xxx@qq.com"); //这里可以是任何邮箱
message.setSubject("标题1111");
message.setText("hello");
// 需要与配置文件发件人的值相同
// message.setFrom("xxx@qq.com"); //QQ邮箱
message.setFrom("xxx@aliyun.com"); //阿里邮箱
message.setFrom("xxx@163.com"); //网易邮箱
message.setSentDate(new Date());
//将邮件对象赋予邮件发送器
mailSender.send(message);
}