SpringBoot如何使用FreeMarker模板发送邮件

发布时间:2021-11-19 15:13

SpringBoot是用来简化新Spring应用的初始搭建以及开发过程的,我们在使用SpringBoot的时候,想要实现FreeMarker模板通过SpringBoot编译发送邮件,我们应该如何进行操作呢?下面给大家分享一下。

一、添加相关依赖

1、使用Maven,在pom.xml添加如下依赖:

<!-- 邮件所需依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency> 

<!-- Spring Boot Freemarker 依赖,发送HTML格式的邮件的方式 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>        
</dependency>

2、使用Gradle,则在 build.gradle 添加依赖:

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-freemarker'
  implementation 'org.springframework.boot:spring-boot-starter-mail'
  //... 其他依赖库
}

二、application.yml 配置

#其他配置信息
spring:
    #其他配置信息
    freemarker:
        suffix: .ftl
        template-loader-path:
          - classpath:/templates
        cache: false
        charset: UTF-8
        content-type: text/html
    mail:
        host: smtp.163.com
        username: #添加您自己163邮箱  
        password: #授权第三方登录的授权码  不是邮箱密码哦  别弄混了
        protocol: smtp
        properties.mail.smtp.auth: true
        properties.mail.smtp.port: 994 #465或者994
        #properties.mail.display.sendmail: Javen
        #properties.mail.display.sendname: Spring Boot Guide Email
        properties.mail.smtp.starttls.enable: true
        properties.mail.smtp.starttls.required: true
        properties.mail.smtp.ssl.enable: true
        default-encoding: utf-8
        from: #添加您自己163邮箱

三、编写MailService服务

@Service
public class MailServiceImpl implements MailService {

 //邮件的发送者
 @Value("${spring.mail.username}")
 private String from;

 //注入MailSender
 @Autowired
 private JavaMailSender mailSender;

 //发送邮件的模板引擎
 @Autowired
 private FreeMarkerConfigurer configurer;

 /**
 * @param params 发送邮件的主题对象 object
 * @param title 邮件标题
 * @param templateName 模板名称
 */
 @Override
 public void sendMessageMail(Object params, String title, String templateName) {

 try {

 MimeMessage mimeMessage = mailSender.createMimeMessage();
 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
 helper.setFrom(from);
 helper.setTo(InternetAddress.parse("xxxxx@163.com"));//发送给谁
 helper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");//邮件标题

 Map<String, Object> model = new HashMap<>();
 model.put("params", params);
 try {
 Template template = configurer.getConfiguration().getTemplate(templateName);
 try {
 String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

 helper.setText(text, true);
 mailSender.send(mimeMessage);
 } catch (TemplateException e) {
 e.printStackTrace();
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 } catch (MessagingException e) {
 e.printStackTrace();
 }
 }
}

四、定义发送邮件对象

发送内容为object,我这里演示一个对象,通过模板渲染方式接收内容

@Data
public class Message {

 private String messageCode;
 private String messageStatus;
 private String cause;

}

五、在项目templates目录新建个message.ftl文件

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title>消息通知</title>
</head>

<style type="text/css">
 table {
 font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
 width: 100%;
 border-collapse: collapse;
 }

 td, th {
 font-size: 1em;
 border: 1px solid #5B4A42;
 padding: 3px 7px 2px 7px;
 }

 th {
 font-size: 1.1em;
 text-align: center;
 padding-top: 5px;
 padding-bottom: 4px;
 background-color: #24A9E1;
 color: #ffffff;
 }
</style>
<body>
<div>
 <h2>邮件消息通知</h2>
 <table id="customers">
 <tr>
 <th>MessageCode</th>
 <th>MessageStatus</th>
 <th>Cause</th>
 </tr>
 <tr>
 <td>${(params.messageCode)!""}</td>
 <td>${(params.messageStatus)!""}</td>
 <td>${(params.cause)!""}</td>
 </tr>
 </table>
</div>
</body>
</html>

六、测试邮件发送

新建controller类

@RestController
public class MailController {

 @Autowired
 private MailService mailService;

 @RequestMapping(value = "/sendMessage", method = RequestMethod.GET)
 public void sendMailMessage() {
 Message message = new Message();

 message.setMessageCode("MissingParameter");
 message.setMessageStatus("Failed");
 message.setCause("缺少参数,请确认");

 mailService.sendMessageMail(message, "测试消息通知", "message.ftl");
 }
}

启动服务访问 http://localhost:8080/sendMessage,最后查看邮箱。

Vue3学习笔记之依赖注入Provide/Inject 网站建设

Vue3学习笔记之依赖注入Provide/Inject

Provide / Inject 通常,当我们需要从父组件向子组件传递数据时,我们使用 props。想象一下这样的结构:有一些深度嵌套的组件,而深层的子组件只需要父组件的部分内容。在这种情况下,如果...
Vue3全局实例上挂载属性方法案例讲解 网站建设

Vue3全局实例上挂载属性方法案例讲解

在大多数开发需求中,我们有时需要将某个数据,或者某个函数方法,挂载到,全局实例身上,以便于,在项目全局的任何位置都能够调用其方法,或读取其数据。 在Vue2 中,我们是在 main.js 中 直...