引入Maven依赖

1
2
3
4
5
6
<!-- email邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>

开启POP3/SMTP服务

位置:QQ邮箱首页->设置->账户,然后会得到一个授权码

img

img

application.yml文件配置

*****处根据自己的实际情况填写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
spring:
# QQ邮箱发送配置
mail:
# host不配置会注入失败
host: smtp.qq.com
#自己的邮箱
username: ****@qq.com
#授权码
password: ****
default-encoding: utf-8
protocol: smtp
properties:
mail:
smtp:
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000
ssl:
enable: true #一定要开启ssl,不然会503 验证失败的(开启加密验证)

Java代码

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
49
50
51
52
53
54
package com.ledao.controller;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
* @author LeDao
* @company
* @create 2021-07-16 9:08
*/
@Controller
public class MyController {

@Resource
private JavaMailSender javaMailSender;

/**
* 首页
*
* @return
*/
@ResponseBody
@RequestMapping("/")
public String root() {
return "<h1 style='text-align: center'><a href='/sendMail'>点我发送邮件</a></h1>";
}

/**
* 发送邮件测试
*
* @return
*/
@ResponseBody
@RequestMapping("/sendMail")
public String sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
//发件人QQ邮箱
message.setFrom("******@qq.com");
//收件人QQ邮箱
message.setTo("******@qq.com");
//主题
message.setSubject("发送邮件测试");
//内容
message.setText("111");
//发送邮件
javaMailSender.send(message);
return "<h2 style='color:red;text-align: center'>发送成功,请到收件人邮箱查收!!</h2>";
}
}

测试与结果

运行项目后,点击发送邮件链接,之后目标邮箱就可以收到邮件了

img