码迷,mamicode.com
首页 > 编程语言 > 详细

使用 FreeMarker模板 Springboot 发送邮件

时间:2018-12-17 14:26:50      阅读:445      评论:0      收藏:0      [点我收藏+]

标签:目录   注入   freemark   代码   servlet   包括   div   发送   .data   

四、使用 FreeMarker模板

    HTML 标签的字符串拼接是一件很棘手的事。因为在你的大脑中解析HTML标签并想象它在渲染时会是什么样子是挺困难的。而将HTML混合在Java代码中又会使得这个问题更加复杂。

    因此 Spring 给出的解决方案是:使用模板生成 HTML 文本,有多种模板方案可供选择,包括Apache Velocity和Thymeleaf。这里仅介绍 Thymeleaf 模板的用法(假设读者已经熟悉了 Thymeleaf 模板并知道如何在 SpringBoot 中使用它们)。

    1、在项目templates目录新建Freemarker模板 —  message.ftl

<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>

2、定义发送邮件渲染对象

发送内容为object,通过模板渲染方式接收内容,如下所示

import lombok.Data;

@Data

public class Message {

    private String messageCode;

    private String messageStatus;

    private String cause;
}

3、在application.properties文件中配置mail信息

spring.mail.host=smtp.exmail.qq.com
spring.mail.username=123456@qq.cn
spring.mail.password=123456
spring.mail.default-encoding=UTF-8

4、编写EmailService服务接口

 

import freemarker.template.Template;

import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
@Service
@Configuration
public class EmailService {
//邮件的发送者
@Value("${spring.mail.from}")
private String from;
//注入MailSender
@Autowired
private JavaMailSender javaMailSender;
//发送邮件的模板引擎
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;

public void sendMessageMail(Object params, String title, String templateName){
try{
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(InternetAddress.parse("zhoucui_test@163.com"));//发送给谁
mimeMessageHelper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");//邮件标题
Map<String,Object> model = new HashMap<>();
model.put("params",params);
try{
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
try{
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);
mimeMessageHelper.setText(text,true);
javaMailSender.send(mimeMessage);
}catch (TemplateException e){
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}catch (MessagingException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
}
 

 

5、新建controller测试

import com.longteng.diamond.domain.Message;
import com.longteng.diamond.service.EmailService;
import freemarker.template.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Controller
public class MimeEmailController {
   
    @Resource
    private EmailService emailService;

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

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

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

访问http://localhost:8081/send 出现1测试成功。

使用 FreeMarker模板 Springboot 发送邮件

标签:目录   注入   freemark   代码   servlet   包括   div   发送   .data   

原文地址:https://www.cnblogs.com/zhou-test/p/10130499.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!