Spring为FreeMarker提供了一个FreeMarkerConfigurer类,通过此类可方便地创建FreeMarker的基础环境,Spring提供FreeMarkerTemplateUtils工具类来完成解析模板的任务。
spring配置文件中bean的配置
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<context:component-scan base-package="com.chinacache" />
<bean id="fm" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="classpath:template"/> //模板所有目录
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">3600</prop> //自动刷新
<prop key="default_encoding">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
</props>
</property>
</bean>
</beans>
maven包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
</dependency>
java
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("buTopchannels", channel);
map.put("retract", retract);
map.put("OperationTime", channel.get(0).getOperationTime());
map.put("title", title);
map.put("salesDirector", channel.get(0).getSalesDirector());
freemarker.template.Template mailTemplate;
String content = null;
try {
mailTemplate = fm.getConfiguration().getTemplate("channel_mail_su.ftl");
content = FreeMarkerTemplateUtils.processTemplateIntoString(mailTemplate, map);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
ftl
<html>
<head>
<style type="text/css">
table {border:solid #add9c0; border-width:0px 1px 1px 0px;
}
td {border:solid #add9c0; border-width:0px 1px 1px 0px; padding:10px 0px;
}
</style>
</head>
<body>
Hi all:${retract}操作时间:${OperationTime}${retract} 公司转出/测试频道带宽总量大约为[${allBandwidth}],超过[${thresholdValue}]的占其中的[${allpercent}]${retract}[${bu}转出/测试频道带宽总量大约为[${buBandwidth}],超过[${thresholdValue}]的占其中的[${bupercent}]<br> ${retract}<font color='red'>第一负责人是:${DutyAdvocate}</font><br>${retract}<font color='red'>备份负责人是:${DutyBack}.</font><br>前[${buTopSize}]的分别是${retract}
<table >
<thead>
<tr>
<th>bu</th>
<th>频道</th>
<th>用户</th>
<th>${title}时间</th>
<th>峰值</th>
<th>流量</th>
<th>销售</th>
<th>客服</th>
<th>频道状态</th>
</tr>
</thead>
<tbody>
<#list buTopchannels as channel>
<tr>
<td>${channel.bu}</td>
<td>${channel.channelName}</td>
<td>${channel.customerName}</td>
<td>${channel.channelTransferTime}</td>
<td>${channel.maxBandwidthStr}</td>
<td>${channel.fluxStr}</td>
<td>${channel.salesDirector}</td>
<td>${channel.customerDirector}</td>
<td>${channel.state}</td>
</tr>
</#list>
</tbody>
</table>
<br><br><br><br><br>如有程序bug请与snp[高保宗]联系
</body>
</html>
转自其它博客的:
Spring为FreeMarker提供了一个FreeMarkerConfigurer类,通过此类可方便地创建FreeMarker的基础环境,Spring提供FreeMarkerTemplateUtils工具类来完成解析模板的任务。
下面以用户注册成功后发送的模板文件registerUser.ftl,将该文件放在src/mailTemplate下:
6.1 模板文件
1. <html>
2. <head>
3. <meta http-equiv="content-type" content="text/html;charset=utf8">
4. </head>
5. <body>
6. 恭喜您成功注册!您的用户名为:<font color='red' size='30'>${username}</font>
7. </body>
8. </html>
1. <html>
2. <head>
3. "content-type" content="text/html;charset=utf8">
4. </head>
5. <body>
6. 'red' size='30'>${username}</font>
7. </body>
8. </html>
上面的${username}标签代表一个可被替换的动态属性。FreeMarker模板的标签支持级联属性,如${user.Id}则表示user对象的Id属性。
6.2 使用FreeMarker模板技术构造邮件内容
1. package com.bb.spring.email;
2. import org.springframework.ui.freemarker.*;
3. import org.springframework.web.servlet.view.freemarker.*;
4. import freemarker.template.*;
5. import ......
6. public class TemplateEmailService {
7. private JavaMailSender sender;
8. private FreeMarkerConfigurer freeMarkerConfigurer=null;//FreeMarker的技术类
9.
10. public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
11. this.freeMarkerConfigurer = freeMarkerConfigurer;
12. }
13.
14. public void setSender(JavaMailSender sender) {
15. this.sender = sender;
16. }
17.
18. //通过模板构造邮件内容,参数username将替换模板文件中的${username}标签。
19. private String getMailText(String username){
20. "";
21. try {
22. //通过指定模板名获取FreeMarker模板实例
23. "registerUser.ftl");
24. //FreeMarker通过Map传递动态数据
25. new HashMap();
26. "username",username); //注意动态数据的key和模板标签中指定的属性相匹配
27. //解析模板并替换动态数据,最终username将替换模板文件中的${username}标签。
28. htmlText=FreeMarkerTemplateUtils.processTemplateIntoString(tpl,map);
29. catch (Exception e) {
30. // TODO Auto-generated catch block
31. e.printStackTrace();
32. }
33. return htmlText;
34. }
35.
36. //发送模板邮件
37. public void sendTemplateMail(String username) throws MessagingException{
38. MimeMessage msg=sender.createMimeMessage();
39. new MimeMessageHelper(msg,false,"utf8");//由于是html邮件,不是mulitpart类型
40. "dongsanbo@sina.com");
41. "dongsanbo@sina.com");
42. "注册成功-模板邮件");
43. //使用模板生成html邮件内容
44. true);
45.
46. sender.send(msg);
47. "成功发送模板邮件");
48. }
49. public static void main(String[] args) throws MessagingException {
50. // TODO Auto-generated method stub
51. new FileSystemXmlApplicationContext(
52. "src/applicationContext.xml");
53. "templateEmail");
54.
55. //发送模板邮件
56. "yefriend");
57. //end method
58. }
6.3 applicationContext.xml配置文件
1. <bean id="freeMarker" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
2. "templateLoaderPath" value="classpath:mailTemplate"/><!--指定模板文件目录-->
3. "freemarkerSettings"><!-- 设置FreeMarker环境属性-->
4. <props>
5. "template_update_delay">1800</prop><!--刷新模板的周期,单位为秒-->
6. "default_encoding">UTF-8</prop><!--模板的编码格式 -->
7. "locale">zh_CN</prop><!-- 本地化设置-->
8. </props>
9. </property>
10. </bean>
11. <bean id="templateEmail" class="com.bb.spring.email.TemplateEmailService">
12. "sender" ref="mailsender"></property>
13. "freeMarkerConfigurer" ref="freeMarker"></property>
14. </bean>
在配置文件中已设置好模板目录,所以可在类中直接用模板文件名来定位模板文件。模板文件用UTF-8编码格式,避免中文乱码。通过设置template_update_delay属性,可让FreeMarker定期刷新模板,从而使应用程序在不重启下更新模板。
至此,可以运行TemplateEmailService类发送邮件,实验表明"yefriend"将替换${username}。
下面是自己的扩展:
实际项目中我们想要动态的指定数据源和模版,就需要如下构造获取方法:
1. public String getMailHtml(Map map, String templateName) {
2. null;
3. try {
4. Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
5. htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
6. catch (IOException e) {
7. e.printStackTrace();
8. catch (TemplateException e) {
9. e.printStackTrace();
10. }
11. return htmlText;
12. }
这样就可以如下获取数据:
1. Map<String,Object> map = amendEmailUtils.initAmendPendingEmailMap(hotelbookheader...);
2. "amendmentPending.ftl");
如果发件人固定,我们还可以让TemplateEmailService 继承org.springframework.mail.SimpleMailMessage这个类,以使用其中的From或to属性
我的类:
1. public class SimpleMailSender extends SimpleMailMessage {
2.
3. private JavaMailSender sender;
4. private MimeMessageHelper messageHellper;
5. private FreeMarkerConfigurer freeMarkerConfigurer;
使用:
1. //类属性
2. public SimpleMailSender mailSender;
3.
4. //方法中
5. Map<String,Object> map = amendEmailUtils.initAmendPendingEmailMap(hotelbookheader...);
6. "amendmentPending.ftl");
7.
8.
9. MimeMessage mimeMessage = mailSender.GetSender().createMimeMessage();
10. new MimeMessageHelper(mimeMessage, true, "utf-8");
11. messageHellper.setSubject(amendSubjectToUser);
12.
13. messageHellper.setFrom(mailSender.getFrom());
14. //如果不继承,自定义类SimpleMailSender中就无from、to方法,就不可从配置文件中获取
xml配置:
1. <bean id="mailSender"
2. class="com.techson.himsnanhwa.admin.mail.SimpleMailSender">
3. "javaMailSender"><ref bean="sender"/></property>
4. "freeMarkerConfigurer" ref="freeMarker"></property>
5. "from">
6. @techson.com.hk</value>
7. </property>
8. "to">
9. @techson.com.hk</value>
10. </property>
11. </bean>
12.
13. <!--配置邮件模板-->
14. "freeMarker" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
15. "templateLoaderPath" value="/mailTemplete"/>
16. "freemarkerSettings">
17. <props>
18. "template_update_delay">15</prop>
19. "default_encoding">UTF-8</prop>
20. "locale">zh_CN</prop>
21. </props>
22. </property>
23. </bean>
24.
25. <bean id="sender"
26. class="org.springframework.mail.javamail.JavaMailSenderImpl">
27. "host">
28. 192.168.108.6</value>
29. </property>
30. "javaMailProperties">
31. <props>
32. "mail.smtp.auth">true</prop>
33. "mail.smtp.timeout">25000</prop>
34. </props>
35. </property>
36. "username">
37. <value>wy</value>
38. </property>
39. "password">
40. <value>wy</value>
41. </property>
42. </bean>
。。。
发送带附件的邮件:
1. MimeMessage message = mailSender.GetSender().createMimeMessage();
2. new MimeMessageHelper(message, true, "utf-8");
3. messageHellper.setSubject(subject);
4. "couemail") + "");
5. messageHellper.setFrom(sender);
6.
7. new MimeMultipart();
8. new MimeBodyPart();
9. new File("E:\\hotel_" + filename + ".xls");
10. new FileDataSource(file);
11. new DataHandler(fds));
12. mbp.setFileName(fds.getName());
13. mp.addBodyPart(mbp);
14.
15. message.setContent(mp);
16. message.saveChanges();
发送成功后可使用
- fds.getFile().delete();
删除文件!
或:
1. String path = ServletActionContext.getServletContext().getRealPath("/download/");
2. String destinct = path + "/" + fileName + ".zip";
3.
4. Resource file = new ServletContextResource(ServletActionContext.getServletContext(),destinct);
5. helper.addAttachment("hotel_nh_"+countryCode + ".zip", file.getFile());
6.
7. 或:
8. "myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
。。。