电子邮件服务器类比于现实中的邮局。用户发邮件时,会将邮件发送到邮件服务器,邮件服务器将邮件再发送到接收方的电子邮箱中。
邮件服务器又可以分为两种类型:
邮件传输协议有如下几种
以QQ邮箱为例
开启后需要生成授权码。
我们来看看纯Java代码发邮件。
send方法就如此之长,而SpringBoot将发送功能封装好了。接下来你将看到用SpringBoot发送邮件是如何的简单。
导入Maven jar包
<!--邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
这里的模板引擎后面需要,这里先导入进来。
application.properties
文件配置
#邮件配置
spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=1587xx3453@qq.com
spring.mail.password=yurzjzmreurpgfdghalouke
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
如果是QQ邮箱发送,你只需要修改username
和password
。password
为上面生成的授权码,不是你邮箱的登录密码哦。
编写邮件发送方法
发送结果
如果我们要发送附件
发送结果如下图
如果需要在正文插入图片
发送结果如下
当然我们也可以使用模板引擎
在resources/templates
目录下创建文件thymeleaf-mail.html
文件。
thymeleaf-mail.html
内容如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>嗨!欢迎关注我的博客:Lvshen的技术小屋:</p>
<table border="1">
<tr>
<td>姓名</td>
<td th:text="${username}"></td>
</tr>
<tr>
<td>性别</td>
<td th:text="${sex}"></td>
</tr>
<tr>
<td>爱好</td>
<td th:text="${hobby}"></td>
</tr>
</table>
<div style="color: #ff1a0e">关注我获取Java学习资料哦</div>
</body>
</html>
编写发送代码
测试结果如下
如果你没有开发过邮件发送或正在开发邮件发送的功能,希望这篇文章可以帮到你。