导入依赖

1
2
3
4
5
<!-- springboot 邮件支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

ymal配置

1
2
3
4
5
6
7
8
spring:
mail:
host: ${MAIL_HOST:smtp.qq.com}
port: ${MAIL_port:465}
protocol: ${MAIL_PROTOCOL:smtps}
default-encoding: UTF-8
username: ${MAIL_USERNAME:xxx@qq.com}
password: ${MAIL_PASSWORD:}

邮件发送服务类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Service
public class MailUtil {
@Value("${spring.mail.username}")
private String from;

@Autowired
private JavaMailSender mailSender;

public void sendMail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
}