目录
1、pom配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、yaml配置
spring:
mail:
# 比如:使用qq邮箱服务(也可以其他服务)
host: smtp.qq.com
#发送方的邮箱
username: xxx@qq.com
# 设置密码,该处的密码是发送方QQ邮箱开启SMTP的授权码而非QQ密码
password: xxxx
default-encoding: UTF-8
properties:
mail:
smtp:
ssl:
enable: true
其他邮箱服务:
smtp.163.com
:163邮箱smtp.126.com
:126邮箱smtp.qq.com
:qq邮箱
3、发送普通文本
代码:
浏览器访问:http://localhost:8080/mail/sendText
查看邮件,内容如下:
4、发送html模板邮箱
代码:
浏览器访问: http://localhost:8080/mail/sendHtml
查看邮件,内容如下:
5、发送附件
代码:
浏览器访问: http://localhost:8080/mail/sendAttachment
查看邮件,内容如下:
6、发送图片
代码:
浏览器访问: http://localhost:8080/mail/sendPicture
查看邮件,内容如下:
7、结合模板引擎发送html邮箱
该方式时,引入thymeleaf
依赖,事先定义好html样式,html里面的参数是动态加载
的,由后端进行控制。与传统的html邮箱相比:可以定义更加复杂的样式、更加灵活的参数显示。
7.1添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
7.2 配置html页面
在resource/templates
下创建mail.html
,代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>用户列表</h1>
<table th:border="1" th:width="200px">
<tr>
<td>用户名</td>
<td>昵称</td>
<td>年龄</td>
</tr>
<tr th:each="user:${userList}">
<td th:width="40%" th:text="${user.username}" th:style="'background-color:'+(${user.odd}?'#fff':'#f5f2eb')"></td>
<td th:width="30%" th:text="${user.nickname}" th:style="'background-color:'+(${user.odd}?'#fff':'#f5f2eb')"></td>
<td th:width="30%" th:text="${user.age}" th:style="'background-color:'+(${user.odd}?'#fff':'#f5f2eb')"></td>
</tr>
</table>
</div>
</body>
</html>
7.3 Java代码
代码:
浏览器访问: http://localhost:8080/mail/sendThymeleaf
查看邮件,内容如下: