# SpringBoot发送简单邮件
本文作者:程序员飞云
# 1. 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
1
2
3
4
5
2
3
4
5
# 2. yml配置
spring:
mail:
host: smtp.qq.com
port: 25
username: xxx # 邮箱账号
password: xxx # 授权码
1
2
3
4
5
6
2
3
4
5
6
# 3. QQ邮箱授权码
在设置,账号里面,开启服务 生成授权码 发送信息 生成授权码(妥善保管)
# 4. 发送简单邮件service
public interface MailService {
void sendEmail();
}
1
2
3
2
3
实现类
@Service
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender javaMailSender;
private String from = "xxxx";
private String to = "xxx";
private String subject = "测试";
private String context = "正文";
/**
* 发送人
* 接收人
* 标题
* 正文
*/
@Override
public void sendEmail() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(from);
mailMessage.setTo(to);
mailMessage.setSubject(subject);
mailMessage.setText(context);
javaMailSender.send(mailMessage);
}
}
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
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
测试
@SpringBootTest
class MailServiceImplTest {
@Resource
private MailServiceImpl mailService;
@Test
void sendEmail() {
mailService.sendEmail();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 5. 高级版本
@Service
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender javaMailSender;
// 发送方
private String from = "xxxx";
private String to = "xxxx";
private String subject = "测试";
private String context = "<a href='https://www.baidu.com'>点击获取</a>";
@Override
public void sendMimeEmail() {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
// 可以设置发送附件
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject(subject);
helper.setFrom(from);
helper.setTo(to);
// 发送链接
helper.setText(context, true);
// 发送附件,file地址
File file = new File("xxxx");
helper.addAttachment(file.getName(), file);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
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
30
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
30