整合Mail
wenking 7/6/2023
# 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
1
2
3
4
2
3
4
# 编写配置
spring:
mail:
host: smtp.qq.com
username: .........
password: .........
default-encoding: UTF-8
1
2
3
4
5
6
2
3
4
5
6
# 编写服务
@Service
public class EmailServiceImpl implements EmailService {
@Value("${spring.mail.username}")
private String fromUser;
@Autowired
private JavaMailSender javaMailSender;
// 发送 txt 邮件
@Override
public void sendEmailServer(String sendUser, String title, String text) {
SimpleMailMessage smm = new SimpleMailMessage();
smm.setFrom(fromUser);
smm.setTo(sendUser);
smm.setSubject(title);
smm.setText(text);
javaMailSender.send(smm);
}
// 发送 包含文件的邮件
@Override
public void sendFileEmailServer(String sendUser, String title, String text, List<String> fileList) {
MimeMessage mm = null;
try {
mm = javaMailSender.createMimeMessage();
MimeMessageHelper mmh = new MimeMessageHelper(mm, true);
mmh.setFrom(fromUser);
mmh.setTo(sendUser);
mmh.setSubject(title);
mmh.setText(text);
for (String path : fileList) {
FileSystemResource fsr = new FileSystemResource(new File(path));
String fileName = path.substring(path.lastIndexOf(File.separator));
mmh.addAttachment(fileName, fsr);
}
javaMailSender.send(mm);
} 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48