您的位置:首页 > 编程语言 > Java开发

Velocity 、Freemarker模板及Spring Api实现发送邮件

2017-07-11 19:32 701 查看

Veloctiy

1、spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean" scope="prototype">
<property name="velocityProperties">
<props>
<prop key="resource.loader">file</prop>
<!--指定模板所在路径-->
<prop key="file.resource.loader.path">D:\workspace_git_2\jd-notice\jd-noticeman-web\src\main\resources\</prop>
<prop key="file.resource.loader.class">
org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</prop>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
</props>
</property>
</bean>

<!--<bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<property name="templateLoaderPath" value="classpath:emailtemplates" />
</bean>-->
</beans>


2、Velocity测试类

import com.alibaba.fastjson.JSON;
import com.jd.notice.mail.vo.Student;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ui.velocity.VelocityEngineUtils;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by wangyingjie1 on 2017/7/6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring-config-email.xml")
public class VelocityEngineUtilsTest {

@Autowired
private VelocityEngine velocityEngine;//spring配置中定义

@Test
public void testRenderMailByConfig() {
//获取vm模板所需的参数信息
Map model = getModelMap();

Object value = JSON.toJSON(new Student(1, "zhangsan" + 1));
model.put("jsonString", value);

System.out.println("getStudentList===========>" + model.get("list"));

renderMailContext(model, "template.vm");
}

private Map getModelMap() {
return new HashMap() {
{
put("name", "zhangsan");
put("sex", "male");
//模板里面嵌套的表格数据
put("list", getStudentList());
}
};
}

//list 里面装的类型是 JSONObject
private List<Object> getStudentList() {
List<Object> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list.add(JSON.toJSON(new Student(i, "zhangsan" + i)));
}

//String jsonString = JSONArray.toJSONString(list);
//System.out.println(jsonString);
return list;
}

/**
* 根据参数及vm模板 渲染邮件内容
*/
public String renderMailContext(Map model, String templateName) {
String result = null;
try {

result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8", model);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println(result);
return result;
}

@Test
public void testRenderMailByCreate() {
//读取固定路径下面的模板文件
readerMailText();
}

public void readerMailText() {
try {

VelocityEngine velocityEngine = new VelocityEngine();

//TODO 指定下载下来的文件所放的路径
velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "D:\\workspace_git_2\\jd-notice\\jd-noticeman-web\\src\\main\\resources\\");
velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

velocityEngine.init();

//TODO 模板的名称
Template template = velocityEngine.getTemplate("template.vm", "UTF-8");

Context context = new VelocityContext();
context.put("name", "zhangsan");
context.put("sex", "male");
context.put("list", getStudentList());

System.out.println("template==============" + template);

StringWriter stringWriter = new StringWriter();

template.merge(context, stringWriter);

System.out.println(stringWriter);

} catch (Exception e) {
e.printStackTrace();
}

}

}


public class Student {

private int sid;
private String sname;

public Student() {
}

public Student(int sid, String sname) {
this.sid = sid;
this.sname = sname;
}

public int getSid() {
return sid;
}

public void setSid(int sid) {
this.sid = sid;
}

public String getSname() {
return sname;
}

public void setSname(String sname) {
this.sname = sname;
}
}


3、Velocity测试模板

===============邮件VM模板=================

$name  =============  $sex
<span>Sent using Velocity Template</span>

#foreach ($!student in $!jsonString)
<tr>
<td>$!student</td>
</tr>
#end

## VM模板中有表格的情况
#foreach ($!student in $!list)
<tr>
<td> $!student.sid </td>
<td> $!student.sname </td>
</tr>
#end


Freemarker

1、Freemarker测试类

import com.alibaba.fastjson.JSON;
import com.jd.notice.mail.vo.Student;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by wangyingjie1 on 2017/7/6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring-config-email.xml")
public class FreeMarkerTemplateUtilsTest {

@Test
public void testRenderMailText() {

Map model = new HashMap() {
{
put("name", "zhangsan");
put("sex", "male");
//模板里面嵌套的表格数据
put("list", getStudentList());
}
};

renderMailText(model, "template.vm");
}

/**
* 根据参数及freemarker模板 渲染邮件内容
*/
public String renderMailText(Map model, String templateName) {

String result = null;
try {

Template template = getTemplate(templateName);

result = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

} catch (Exception e) {
e.printStackTrace();
}

System.out.println(result);

return result;
}

//list 里面装的类型是 JSONObject
private List<Object> getStudentList() {
List<Object> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list.add(JSON.toJSON(new Student(i, "zhangsan" + i)));
}

//String jsonString = JSONArray.toJSONString(list);
//System.out.println(jsonString);
return list;
}

private Template getTemplate(String templateName) throws IOException {

//todo 优先取缓存 --> key   缓存没有则去JSS上下载模板

File file = new File("D:\\workspace_git_2\\jd-notice\\jd-noticeman-web\\src\\main\\resources\\");
Configuration config =  Configuration.getDefaultConfiguration();
FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(file);
config.setTemplateLoader(fileTemplateLoader);

//todo 需将模板放缓存

return config.getTemplate(templateName, "UTF-8");
}

}


2、Freemarker测试模板

===============邮件FreeMarker模板=================
<html>
<body>
<h3>User name: $name has been deleted.</h3>
<h6>Detail:</h6>
<div>
<p>user name : ${name} .</p>
<p>user sex : ${sex} .</p>
</div>
<span>Sent using FreeMarker Template</span>
</body>
</html>

## FreeMarker模板中有表格的情况
<#list list as student>
<tr>
<td> ${student.sid} </td>
<td> ${student.sname} </td>
</tr>
</#list>


Velocity及Freemarker使用StringReader处理模板

使用StringReader加载并渲染模板文件的示例代码如下:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
* @author: wangyingjie1
* @version: 1.0
* @createdate: 2017-09-01 17:58
*/
public class TemplateStringReaderTest {

@Test
public void freemarkerLoadTemplateFromString() throws IOException, TemplateException {

String template = "<#list students as student>\n" +
"    <tr>\n" +
"        <td> ${student.sid} </td>\n" +
"        <td> ${student.sname} </td>\n" +
"    </tr>\n" +
"</#list>\n";

Map<String, Object> model = Maps.newHashMap();
model.put("name", "zhangsan");
model.put("sex", "不详");

String jsonstr = "[{\"sid\":\"001\",\"sname\":\"Dong qiang\"},{\"sid\":\"002\",\"sname\":\"Jack ma\"}]";
JSONArray objects = JSON.parseArray(jsonstr);
model.put("students", objects);

//model序列化反序列化
String jsonString = JSON.toJSONString(model);
Map parseModel = JSON.parseObject(jsonString, Map.class);

Configuration defaultConfiguration = Configuration.getDefaultConfiguration();

Template t = new Template("alarmTemplate", new StringReader(template), defaultConfiguration);

StringWriter writer = new StringWriter();
t.process(parseModel, writer);

System.out.println(writer);
}

@Test
public void velocityLoadTemplateFromString() {
/**
* Prepare context data
*/
VelocityContext context = new VelocityContext();
context.put("site", "BE THE CODER");
context.put("tutorial_name", "Apache Velocity");

StringWriter writer = new StringWriter();
String templateStr = "$tutorial_name tutorials by $site";

/**
* Merge data and template
*/
Velocity.evaluate(context, writer, "log tag name", templateStr);
System.out.println(writer);
}
}


Spring邮件发送处理

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
* Created by wangyingjie1 on 2017/7/7.
*
*
*/
public class SpringJavaMailSenderTest {

public static void main(String[] args) {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.jd.com");

// TODO username 为公共邮箱前缀
mailSender.setUsername("yingjie1");
mailSender.setPassword("xxxxxxxxxxx");

// org.springframework.mail.javamail.MimeMessageHelper  类可以实现邮件附件的发送
// spring 的api
SimpleMailMessage smm = new SimpleMailMessage();

// TODO 注意发件人的地址必须有 @jd.com
smm.setFrom("xxxxx1@jd.com");

smm.setTo("yyyyyyyyyy@jd.com");
smm.setSubject("Hello world");
smm.setText("Hello world via spring mail sender");

// TODO 执行邮件发送
mailSender.send(smm);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息