1,导入需要的包

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2,添加配置

添加配置前先要到邮箱设置里开启SMTP服务

application.yml

spring:
mail:
host: smtp.qq.com
username: xxxxxxx@qq.com #发送邮件人的邮箱
password: xxxxx #这个密码是邮箱设置里SMTP服务生成的授权码
default-encoding: UTF-8

3,编写发送邮箱的类

 接收类MailDO.java

package com.bootdo.oa.domain;

import java.util.Map;

/**
* 邮件接收参数
*/ public class MailDO { //标题
private String title;
//内容
private String content;
//接收人邮件地址
private String email;
//附加,value 文件的绝对地址/动态模板数据
private Map<String, Object> attachment; public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Map<String, Object> getAttachment() {
return attachment;
} public void setAttachment(Map<String, Object> attachment) {
this.attachment = attachment;
}
}

MailService.java

package com.bootdo.oa.service;

import com.bootdo.oa.domain.MailDO;

public interface MailService {

    void sendTextMail(MailDO mailDO);

    void sendHtmlMail(MailDO mailDO,boolean isShowHtml);

    void sendTemplateMail(MailDO mailDO);
}

MailServiceImpl.java

package com.bootdo.oa.service.impl;

import com.bootdo.common.exception.SystemException;
import com.bootdo.oa.domain.MailDO;
import com.bootdo.oa.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context; import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File; /**
* 发送邮件
*/
@Service
public class MailServiceImpl implements MailService { private final static Logger log = LoggerFactory.getLogger(MailServiceImpl.class); //template模板引擎
@Autowired
private TemplateEngine templateEngine; @Autowired
private JavaMailSender javaMailSender; @Value("${spring.mail.username}")
private String from; /**
* 纯文本邮件
* @param mail
*/
@Async //不解释不懂自行百度,友情提示:有坑
@Override
public void sendTextMail(MailDO mail){
//建立邮件消息
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from); // 发送人的邮箱
message.setSubject(mail.getTitle()); //标题
message.setTo(mail.getEmail()); //发给谁 对方邮箱
message.setText(mail.getContent()); //内容
try {
javaMailSender.send(message); //发送
} catch (MailException e) {
log.error("纯文本邮件发送失败->message:{}",e.getMessage());
throw new SystemException("邮件发送失败");
}
} /**
* 发送的邮件是富文本(附件,图片,html等)
* @param mailDO
* @param isShowHtml 是否解析html
*/
@Async
@Override
public void sendHtmlMail(MailDO mailDO, boolean isShowHtml) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//是否发送的邮件是富文本(附件,图片,html等)
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
messageHelper.setFrom(from);// 发送人的邮箱
messageHelper.setTo(mailDO.getEmail());//发给谁 对方邮箱
messageHelper.setSubject(mailDO.getTitle());//标题
messageHelper.setText(mailDO.getContent(),isShowHtml);//false,显示原始html代码,无效果
//判断是否有附加图片等
if(mailDO.getAttachment() != null && mailDO.getAttachment().size() > 0){
mailDO.getAttachment().entrySet().stream().forEach(entrySet -> {
try {
File file = new File(String.valueOf(entrySet.getValue()));
if(file.exists()){
messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
}
} catch (MessagingException e) {
log.error("附件发送失败->message:{}",e.getMessage());
throw new SystemException("附件发送失败");
}
});
}
//发送
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
log.error("富文本邮件发送失败->message:{}",e.getMessage());
throw new SystemException("邮件发送失败");
}
} /**
* 发送模板邮件 使用thymeleaf模板
* 若果使用freemarker模板
* Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
* configuration.setClassForTemplateLoading(this.getClass(), "/templates");
* String emailContent = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);
* @param mailDO
*/
@Async
@Override
public void sendTemplateMail(MailDO mailDO) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
messageHelper.setFrom(from);// 发送人的邮箱
messageHelper.setTo(mailDO.getEmail());//发给谁 对方邮箱
messageHelper.setSubject(mailDO.getTitle()); //标题
//使用模板thymeleaf
//Context是导这个包import org.thymeleaf.context.Context;
Context context = new Context();
//定义模板数据
context.setVariables(mailDO.getAttachment());
//获取thymeleaf的html模板
String emailContent = templateEngine.process("/mail/mail",context); //指定模板路径
messageHelper.setText(emailContent,true);
//发送邮件
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
log.error("模板邮件发送失败->message:{}",e.getMessage());
throw new SystemException("邮件发送失败");
}
}
}

差点忘了还有个模板 mail.html

放在templates/mail目录下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<h3>你看我<span style="font-size: 35px" th:text="${username}"></span>, 哈哈哈!</h3>
</body>
</html>

4,测试

单元测试启动太慢了,直接写controller测试

   @GetMapping("/testMail")
public R mail(MailDO mailDO){
try {
mailService.sendTextMail(mailDO);
} catch (Exception e) {
return R.error(e.getMessage());
}
return R.ok();
} @GetMapping("/htmlMail")
public R mail(MailDO mailDO){
try {
Map<String,Object> map = new HashMap<>();
map.put("附件名","附件的绝对路径");
mailDO.setAttachment(map);
mailService.sendHtmlMail(mailDO,false);
} catch (Exception e) {
return R.error(e.getMessage());
}
return R.ok();
}    @GetMapping("/templateMail")
public R mail(MailDO mailDO){
try {
Map<String,Object> map = new HashMap<>();
map.put("username","我变大了");
mailDO.setAttachment(map);
mailService.sendTemplateMail(mailDO);
} catch (Exception e) {
return R.error(e.getMessage());
}
return R.ok();
}

5,测试结果

收工。

最简单的 springboot 发送邮件,使用thymeleaf模板的更多相关文章

  1. 7 — 简单了解springboot中的thymeleaf

    1.官网学习地址 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html 2.什么是thymeleaf? 一张图看明白: 解读: ...

  2. 记录一次简单的springboot发送邮件功能

    场景:经常在我们系统中有通过邮件功能找回密码,或者发送生日祝福等功能,今天记录下springboot发送邮件的简单功能 1.引入maven <!-- 邮件开发--><dependen ...

  3. 解决SpringBoot项目中Thymeleaf模板的中文乱码问题

    1.使用IDEA创建SpringBoot项目 package com.example.demo; import org.springframework.boot.SpringApplication; ...

  4. SpringBoot中使用Thymeleaf模板

    1.引入pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId& ...

  5. SpringBoot 之Thymeleaf模板.

    一.前言 Thymeleaf 的出现是为了取代 JSP,虽然 JSP 存在了很长时间,并在 Java Web 开发中无处不在,但是它也存在一些缺陷: 1.JSP 最明显的问题在于它看起来像HTML或X ...

  6. Spring Boot2(五):使用Spring Boot结合Thymeleaf模板引擎使用总结

    一.Thymeleaf概述 一般来说,常用的模板引擎有JSP.Velocity.Freemarker.Thymeleaf . SpringBoot推荐的 Thymeleaf – 语法更简单,功能更强大 ...

  7. Thymeleaf模板引擎的使用

    Thymeleaf模板引擎的使用 1.模板引擎 JSP.Velocity.Freemarker.Thymeleaf 2.springboot推荐使用Thymeleaf模板引擎 特点:语法更简单,功能更 ...

  8. (二)springboot整合thymeleaf模板

    在我们平时的开发中,用了很久的jsp作view显示层,但是标签库和JSP缺乏良好格式的一个副作用就是它很少能够与其产生的HTML类似.所以,在Web浏览器或HTML编辑器中查看未经渲染的JSP模板是非 ...

  9. SpringBoot系列——Thymeleaf模板

    前言 thymeleaf是springboot官方推荐使用的java模板引擎,在springboot的参考指南里的第28.1.10 Template Engines中介绍并推荐使用thymeleaf, ...

随机推荐

  1. 使用synchronized的几种场景

    1.修饰一个方法synchronized 修饰一个方法很简单,就是在方法的前面加synchronized,例如: public synchronized void method() { // todo ...

  2. 推荐一款关于MongoDB日志分析的工具--Mtools

    一. 需求背景 MongoDB数据库的强大的文档模型使其成为处理数据的最佳方式.文档适用于广泛的流行数据模型,支持各种各样的场景.文档模型可以包含键值.关系数据集和图形数据集,当然,还可以包含父子关系 ...

  3. Linux 中磁盘阵列RAID10配置

    首先,了解一下RAID是什么?(百度所得) 独立磁盘冗余阵列(RAID,redundant array of independent disks)是把相同的数据存储在多个硬盘的不同的地方(因此,冗余地 ...

  4. 扒一扒EOS的前世今生

    扒一扒EOS的前世今生 EOS是什么?   EOS可以认为是Enterprise Operation System的缩写,即商用的一款分布式区块链操作系统,EOS主要为了解决百万级用户的使用问题,为企 ...

  5. SQLServer之通过视图修改数据

    通过视图增删改数据注意事项 需要对目标表的 UPDATE.INSERT 或 DELETE 权限(取决于执行的操作). 如果视图引用多个基表,则不能删除行. 如果视图引用多个基表,只能更新属于单个基表的 ...

  6. frameset基础了解

    frameset 元素可定义一个框架集.它被用来组织多个窗口(框架). 列子:一个分为头部导航栏.左边目录.右侧主体信息.(暂时没设计底部栏) <frameset rows="100, ...

  7. VMware虚拟机系统无法使用桥接联网

    1.环境 VMware 14.1.1 虚拟系统:Windows Server 2008 32位 2.解决办法 打开虚拟网络编辑器 有红框中的提示出现时,就点击更改设置 点击桥接模式,在VMnet信息中 ...

  8. sklearn使用——梯度下降及逻辑回归

    一:梯度下降: 梯度下降本质上是对极小值的无限逼近.先求得梯度,再取其反方向,以定步长在此方向上走一步,下次计算则从此点开始,一步步接近极小值.需要注意的是步长的取值,如果过小,则需要多次迭代,耗费大 ...

  9. Jenkins+git+gitlab实现持续自动集成部署

    1  实验环境 三台服务器 gitlab        192.168.7.139 Jenkins    192.168.7.140 java          192.168.7.141 [root ...

  10. ASP.NET MVC学习系列(4)——MVC过滤器FilterAttribute

    1.概括 MVC提供的几种过滤器其实也是一种特性(Attribute),MVC支持的过滤器类型有四种,分别是:AuthorizationFilter(授权),ActionFilter(行为),Resu ...