一、前言

      在上一篇博客中小编向大家介绍了发送带附件的邮件,实践一下也是不错的。这一篇博客是为下一篇博客进行铺垫的,因为项目中需要一个推送的功能,要把推送的信息灵活的显示到一个固有的模板上。所以为了达到这个目的,小编就引入了freemarker。下面向大家介绍。

二、What is Apache FreeMarker?

      FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。【百度百科】




【java】javamail+freemarker生成邮件模板,并发送邮件_java


      既然他是一个模板引擎,所以可以通过固定的模板,然后把数据补充进去,就可以达到使用的目的了。 我们有了模板+数据,再由freemarker组合就可以生成我们要的界面。

      这种方法通常被称为MVC(模型视图控制器)模式,并且特别适用于动态网页。它有助于将网页设计师(HTML作者)与开发人员(Java程序员通常)分开。设计师不会在模板中面对复杂的逻辑,并且可以改变页面的外观,而不需要修改或重新编译代码。

三、生成邮件模板并发送

      可以先看一下我的设计模板样式,其中的所有的数据都需要是可变化的:



【java】javamail+freemarker生成邮件模板,并发送邮件_freemarker_02


      推荐几篇博客:


一篇很全面的freemarker教程



Java: FreeMarker的配置和使用



freemarker语法总结


四、小结

4.1 环境说明

  • freemarker.jar
  • mail.jar
  • FreeMarkerIDE,包含两个文件features和plugins,放到eclipse中。

4.2 具体

      freemarker工具类:

      这里要提示的是cfg.setClassForTemplateLoading(this.getClass(), “/com/dmsd/mail/ftl”);指明了模板存放的位置。

package com.dmsd.freemarker.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


public class FreemarkerUtil {

    /**
     * 获取模板信息
     * @param name 模板名
     * @return
     */
    public Template getTemplate(String name){
        //通过freemarkerd COnfiguration读取相应的ftl
        Configuration cfg = new Configuration();
        //设定去哪里读取相应的ftl模板文件,指定模板路径
        cfg.setClassForTemplateLoading(this.getClass(), "/com/dmsd/mail/ftl");
        try {
            //在模板文件目录中找到名称为name的文件
            Template template =  cfg.getTemplate(name);
            return template;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    } 
    /**
     * 输出到控制台
     * @param name
     * @param root
     * @throws TemplateException
     * @throws IOException
     */
    public void print(String name,Map<String,Object> root) throws TemplateException, IOException {
        //通过Template可以将模板文件输出到相应的流
        Template template = this.getTemplate(name);
        template.process(root, new PrintWriter(System.out));
    }

    /**
     * 输出到文件中
     * @param name
     * @param root
     * @throws TemplateException
     * @throws IOException
     */
    public void fprint(String name,Map<String,Object> root,String outFile)  {
        FileWriter out=null;
        try {
            out = new FileWriter(new File("E:/"+outFile));
            //获取模板
            Template template = this.getTemplate(name);
            //设置模板编码
            template.setEncoding("utf-8");
            try {
                //输出
                template.process(root, out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }finally{
            try {
                if (out!=null) {
                    out.close();
                }
            } catch (Exception e2) {
            }
        }
    }
}

      Object类:提供数据

package com.dmsd.test;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import org.junit.Before;
import org.junit.Test;


import com.dmsd.freemarker.util.FreemarkerUtil;
import com.dmsd.mail.model.Itoo;

import freemarker.template.TemplateException;


public class testfreemarker {
    FreemarkerUtil fuFreemarkerUtil;
    Map<String, Object> root = null;

    @Before
    public void setUp(){
        fuFreemarkerUtil=new FreemarkerUtil();
        root = new HashMap<String, Object>();
    }

    private void sprint(String name) throws TemplateException, IOException{
        fuFreemarkerUtil.print(name, root);
    }

    private void fprint(String name,String filename) {
        fuFreemarkerUtil.fprint(name, root, filename);
    }

    /**
     * ITOO模板
     * @throws Exception
     */
    @Test
    public void testCreateHtml() throws Exception{

        Date date=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        String time=format.format(date);

        Itoo itooList=  new Itoo(
                        "解聘通知书",
                        time,
                        "欢迎使用ITOO云平台",
                        "站在巨人的肩膀上",
                        "http://www.tfjybj.com",
                        "http://192.168.22.208/group1/M00/00/00/wKgW0Fkjp0SANTXDAAGh7DpPo2E431_big.png",
                        "http://baike.baidu.com/link?url=fl7uIbBoz9rWvJ8g2kSdcM7a-NRttA2gDQxu6pH9CLwkKgJ3Wl_Z1zn2OoqgxJhXenjdOyn3Bde5mH_hoJwytuC7Joj2hQCcyspGqAe1Bvx59pUq5RSoukPqdxI96NIH",
                        "不怕不知道,就怕不知道",
                        "http://192.168.22.208/group1/M00/00/00/wKgW0FkjqMqAGm-3AABvODFU6hI303_big.jpg",
                        "18333602097@163.com"
                        );

        root.put("itooList", itooList);

        this.sprint("index.ftl");
        this.fprint("index.ftl", "Ares.html"   );

    }
}

      模板:index.html
      在这个模板中,使用<#include “head.ftl”>引入了其他的模板。

      index.ftl:

<html>
  <head>
    <title>index.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
 <body>
 <div style="padding:40px 0; height:auto; min-height:100px; text-align:center;">
            <div align="center" style="margin:0 auto; min-width:290px; max-width:750px;">
                <div style="margin:0; background:#fff; border-radius:8px;">
                    <#include "head.ftl">
                    <#include "QEcode.ftl">
                </div>  
                    <#include "footer.ftl"> 
                </div>
            </div>
        </div>
    </body>
</html>

      head.ftl:

<div style="background:#f2f2f2;">
    <div style="background:url(http://192.168.22.208/group1/M00/00/00/wKgW0FkjpfqAJAPnAAAlhmNDKpE469_big.png) center top #f2f2f2 no-repeat; height:191px; text-align:left; position:relative; border-radius:8px 8px 0 0;">
        <div style="padding:26px 0 0; color:#fff; font-size:42px; font-weight:100; text-align:center;">${itooList.title}</div>

        <div style="margin:5px 0 0; color:#fff; font-size:20px; font-weight:100; text-align:center;">${itooList.date}</div>

        <div style="margin:15px 0 30px; padding:0 10px; color:#fff; font-size:16px; font-weight:100; line-height:1.4; text-align:center;">${itooList.welcome}</div>
    </div>
</div>

<div style="margin:10px 0 0; padding:0 10px; font-size:18px; color:#363c4c;">
<pre>
<p>
张先生:<br/>
         您于2013年9月1日在我公司单担任 总经理 职务,<br/>
         根据公司有关规定及您的工作绩效和表现,您不适合本公司此职位,<br/>
         故决定自2017年5月23日起,本公司解除与您的聘雇劳动关系,<br/>
         请在收到通知书二日内在公司办公室办理相关离职手续。<br/>
         非常感谢您在本公司的辛勤工作!同时祝愿您在未来有更好的发展!<br/>
</p>
</pre>
</div>

<div style="background:#fff; position:relative; margin:10px 20px 0; padding:0 0 60px; border-bottom:1px solid #f1f1f1; border-radius:3px;">

    <div style="padding:40px 0 0; font-size:34px;">${itooList.notice}</div>
    <div style="margin:10px 0 0; padding:0 10px; font-size:18px; color:#363c4c;">变是永远<span style="font-size:40px; color:#f44336; font-style:italic;">不变</span> 的</div>
    <div style="margin:10px 0 0; padding:0 10px; font-size:18px; color:#363c4c;">没有教不好的学生,只有不会教的老师!</div>
</div>

      QEcode.ftl:

<div>
    <div>
                        <a href="${itooList.logolink}" style="margin:30px 0 0; width:300px; display:inline-block; text-decoration:none; color:##363c4c;" target="_blank"><img src="${itooList.logo}" style="
                        width: 150px;
                    "></a>
                    </div>

                    <div style="margin:5px 0 0; font-size:16px; color:#363c4c;">
                        <a href="${itooList.teacherlink}" style="margin:30px 0 0; width:300px; display:inline-block; text-decoration:none; color:##363c4c;" target="_blank">${itooList.teacherword}</a>
                    </div>

                    <div style="margin:30px 0 0; width:300px; display:inline-block;">
                        <div><img src="${itooList.QRcode}"style="width: 150px;"></div>

                        <div style="margin:5px 0 0; font-size:16px; color:#363c4c;">扫一扫关注公众号</div>
                    </div>
                    </div>

      footer.ftl:

<br/>
<div style="background:#3587f2; padding:12px; line-height:1.8; font-size:14px; color:#fff;">提示:请不要对此邮件直接回复,系统看不懂您的回信^_^。如果您有建议或意见,请回复
    <a href="mailto:${itooList.email}" style="text-decoration:none; color:#fff;">${itooList.email}</a>
</div>


<div style="background:url(http://192.168.22.208/group1/M00/00/00/wKgW0FkjpiuAO_ZOAAAC3nG29KQ692_big.png) bottom repeat-x; height:90px; border-radius:0 0 8px 8px; position:relative;">
</div>

      生成效果:



【java】javamail+freemarker生成邮件模板,并发送邮件_freemarker_03


      发送邮件后,可以借鉴《【java】javamail简介以及发送邮件》

四、小结

      通过对freemarker的使用,其中的一些标签等使用也是比较重要的,还有就是存储数据的时候,要把数据放入到map中,然后在前台取。