0
点赞
收藏
分享

微信扫一扫

SpringBoot整合JavaMailSender实现邮件发送

是波波呀 2022-02-17 阅读 144

目录

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

查看邮件,内容如下:
在这里插入图片描述

举报

相关推荐

0 条评论