首页 > 编程语言 >【java】javamail+freemarker生成邮件模板,并发送邮件

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

时间:2023-05-06 20:06:42浏览次数:62  
标签:java name freemarker 邮件 template import 模板


一、前言

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

二、What is Apache FreeMarker?

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




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


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

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

三、生成邮件模板并发送

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



【java】javamail+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",
                        "[email protected]"
                        );

        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中,然后在前台取。


标签:java,name,freemarker,邮件,template,import,模板
From: https://blog.51cto.com/u_16100820/6251081

相关文章

  • 【微信】Java 微信扫码支付(模式二)
    一、前言      今天是一个有意义的日子,八月十五中秋节。      在这个这么有意义的日子里,小编写下这篇博客,自己的记忆肯定非常深,哈哈哈,先自嘲一下。      记得小编的前一篇关于微信的博客中提到了,微信是一种生活方式,有九亿人在使用。中国各个地区都已经使用上了微......
  • java根据IP获取城市代码
    关键字:java根据IP获取城市代码附件是一个java工程,其中qqwry0910.rar是腾讯的软件,它可以时时更新你的QQWry.dat,而QQWry.dat是一个IP数据库,我们通过java可以直接根据IP获取城市及网络(如:北京市|联通),为了让数据库永远是最新的,可以通过qqwry0910.rar来在线升级,......
  • 怎么准备Java面试(一):全局把控
    一、前言最近小编换工作,也要开始准备一下面试。小编作为一个Java开发,也是从初级——>中级——>高级——>资深。一步一步走过来的,基本面试过程中,内容是大致是一样的。下面我将从这几个分支中来依次铺展开:二、聊一聊面试大部分公司会有:一面基础面试or算法;二面项目组长深入面试......
  • (转)Java中的String、StringBuilder和StringBuffer
    1、StringString对象是不可变的,即一旦一个String对象被创建以后,包含在这个对象中的字符序列是不可改变的,直至这个对象被销毁。那么我们new一个String对象,比如Stringa=newString("A")Stringa2=newString("A")和直接创建一个字符串,比如Stringb="A"这两种方......
  • 如何理解理解Java对象与引用?
    一、关于对象与引用之间的一些基本概念  为便于说明,先定义一个类:classVehicle{intpassengers;intfuelcap;intmpg;}有了这个类,就可以用它来创建对象: Vehicleveh1=newVehicle() ,通常把这条语句的动作称之为创建一个对象,其实,它包含了四个动作:newVehicleVehicleveh1= ......
  • JavaScript封装大全
    JavaScript封装大全-持续更新Ajax封装//使用该封装需注意//Ajax(method(默认GET),url(网址必传),success(res){(成功时数据处理函数必传)},error(res)(失败时数据处理函数),data(网址中qurey部分用对象形式存储默认为空))//使用ES6语法classAjax{//解构传......
  • k10_java数据类型
    数据类型强类型语言java是强类型语言要求变量的使用过要严格符合规定,所有的变量需要先定义后才能使用。弱类型语言就是类型定义不太严格,变量名可以不可以直接使用,或者直接定义个变量名,不用声明其类型java数据类型分类————Java的数据类型分为两类基本数......
  • 28基于java的简单酒店数据管理
    本文章介绍一个基于java的简单酒店数据管理系统项目介绍该项目适用于初学java后,需要一个小练手的javaweb项目,该项目是只有一个酒店数据表,然后实现对该酒店增加,修改,删除和分页查询的小案例,虽然项目不是很复杂,但麻雀虽小但五脏俱全,适合于个人学习适用。项目使用的技术架构后......
  • java filter过滤器 读取配置文件properties的值
    http://www.yayihouse.com/yayishuwu/chapter/29811.获取application.properties的值如userId=1 2.一般实体中采用@Value既可获取@Value("userIdl")privateStringuserId; 但是在filter中,需要用上下文对象来获取filter的生命周期如下:web应用程序启动时,web服务器将创......
  • Java之Object类
    1、Object类概述 Object类存储在java.lang包中,是所有java类(Object类除外)的终极父类(可以在代码中明确地写出声明要“继承Object类”,没有任何错误)。当然,数组也继承了Object类。但是,接口是不继承Object类的。接口只是是抽象类的延伸,可以将它看做是纯粹的抽象类,接口中的所有方法,......