【笔记】SpringBoot项目整合JavaMailSender

前言

SpringBoot项目整合JavaMailSender,实现发邮件

添加依赖

pom.xml
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

修改配置文件

application.properties
1
2
3
4
5
6
7
8
9
10
11
server.port=80

spring.mail.host=smtp.qq.com
# 邮箱
spring.mail.username=
# 邮箱的密码或授权码
spring.mail.password=
spring.mail.default-encoding=utf-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class MainService {

@Autowired
JavaMailSender javaMailSender;

public void sendMail(String subject, String text) {
//创建一封邮件
SimpleMailMessage mailMessage = new SimpleMailMessage();
//设置收件人
mailMessage.setTo("000000@qq.com");
//设置发件人
mailMessage.setFrom("000000@qq.com");
//设置标题
mailMessage.setSubject(subject);
//设置正文
mailMessage.setText(text);
//发送邮件
javaMailSender.send(mailMessage);
}

}

完成