利用Freemarker模板发送邮件

该博客介绍了如何利用Freemarker模板引擎配合Spring发送邮件。内容包括Freemarker的基本概念,通过spring-FreeMarkerConfigurer配置XML文件,从beanFactory获取Template文件,以及详细讲解了发送邮件的过程和使用的template.ftl模板。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Freemarker简介

FreeMarker是一个模板引擎,由java编写,与容器无关,非WEB项目也可使用。
具体介绍:http://demojava.iteye.com/blog/800204

利用spring-FreeMarkerConfigurer发送邮件

配置xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans
                     http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
    default-autowire="byName" default-lazy-init="true">



    <!-- 模板参数配置 -->
    <bean id="messageConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPaths">
            <list>
                <value>/WEB-INF/test/template/freemarker/</value>
                <value>/WEB-INF/test/template/freemarker/layout/</value>
            </list>

        </property>
        <!--locale:该选项指定该模板所用的国家/语言选项
            number_format:指定格式化输出数字的格式
            boolean_format:指定两个布尔值的语法格式,默认值是true,false
            date_format,time_format,datetime_format:指定格式化输出日期的格式
            time_zone:设置格式化输出日期时所使用的时区
            -->
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">utf-8</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="classic_compatible">true</prop>
            </props>
        </property>
    </bean>

</beans>

获取Template文件

1.从spring beanFactory中获取FreeMarkerConfigurer
2.从FreeMarkerConfigurer获取Template,存入缓存Map中

package com.ucar.oam;

import com.zuche.framework.common.SpringApplicationContext;
import com.zuche.framework.utils.Assert;
import freemarker.template.Template;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 利用FreeMarker获取Template发送邮件
 */
public class FreeMarkerUtil {

    private static FreeMarkerConfigurer freeMarkerConfigurer = null;

    //用于缓存 <TemplateName,Template>
    private static ConcurrentHashMap<String, Template> templateMap = new ConcurrentHashMap<String, Template>();

    /**
     * 加载 template到templateMap中
     */
    private static  void refreshTemplate() {
        if (freeMarkerConfigurer == null) {
           freeMarkerConfigurer = (FreeMarkerConfigurer) SpringApplicationContext.getBean("messageConfig");
        }
        if (templateMap != null && !templateMap.isEmpty()) {
            templateMap.clear();
        }
        for (String temName : TemplateConstant.temNames) {
            templateMap.put(temName, loadTemplate(temName));
        }

    }

    /**
     * @Description:按template名加载,实际加载执行代码
     * @param temName
     * @return Template
     */
    private static Template loadTemplate(String temName) {
        Assert.notNull(temName);
        Template template = null;
        try {
//            FreeMarkerConfigurer freeMarkerConfigurer = (FreeMarkerConfigurer) SpringApplicationContext.getBean("freemarker.mailAndMessageConfig");
            template = freeMarkerConfigurer.getConfiguration().getTemplate(temName);
            return template;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Description:对外提供的获取Template的方法
     * 示例:FreeMarkerUtil.getTemplate(temName)
     * @exception if <code>null</code> throw <code>RuntimeException</code>
     * @param temName template名称
     * @return Template
     */
    public static Template getTemplate(String temName) {

        if (templateMap.isEmpty() || templateMap.size() < 1) {
            refreshTemplate();
        }
        Template template = templateMap.get(temName);
        if (template == null) {
            template = loadTemplate(temName);
            if (template != null) {
                templateMap.put(temName, template);
            }
        }
        if (template == null) {
            throw new RuntimeException("模板不存在:" + temName);
        }
        return template;
    }

    /**
     * 生成模板页面字符串
     * @param templateName        模板文件名(含后缀)
     * @param pageObjectMap       页面显示使用的组合Map
     * @return
     * @throws Exception
     */
    public static String getHtmlPageStr(String templateName,Map<String,?> pageObjectMap) throws Exception{
        Template template=getTemplate(templateName);
        return FreeMarkerTemplateUtils.processTemplateIntoString(template, pageObjectMap);
    }


}

发送邮件

MailMessage mailMessage = new MailMessage();
        Map pageObjectMap  = new HashMap();
        pageObjectMap.put("content",content);
        mailMessage.setContent(FreeMarkerUtil.getHtmlPageStr("template.ftl",pageObjectMap));
        mailMessage.send();

模板 template.ftl

<html>  
<head>  
<meta http-equiv="content-type" content="text/html;chartset=utf-8"; >  
</head>  
<body>  
尊敬的 用户:  
您好欢迎使用本邮件系统!  
<font size=20 color='red'>  
以下是内容:  
${content}  
</font>  
</body>  
</html>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值