前言:上一篇博文讲解了邮件发送的基础用法(数据是写死的),然而在实际开发中,大多数情况下邮件内容都是根据业务来动态生成的。所以在此篇博文中,我们将讲解邮件发送携带数据的几种方案。

一、解析自定义占位符

  实现方法: 通过解析自定义占位符,将传递到邮件中的数据,转换成html内容,进行发送。

1)占位符替换函数

/**
* Replaces place holder ("${}") string in template with values in Map
*
* @param template
* @param models
* @return
*/
public static String replacePlaceHolder(String template, Map<String, String> models) { if (template.indexOf("${") == -1) {
return template;
} while (true) { int start = template.indexOf("${");
int end = template.indexOf("}", start); if (start != -1 && end != -1) { String key = template.substring(start + 2, end); if (models.containsKey(key)) {
template = template.substring(0, start) + models.get(key) + template.substring(end + 1);
} } else {
break;
} } return template; }

2) 邮件发送Test-Case

// 1. Resolve html template to real text
String htmlTemplate = "<html lang='zh-cn'><head></head><body><h1>发送带模板数据的Email</h1><p>你好,${username}。本次您的验证码为${code},请妥善保管</p></body></html>"; Map<String, String> models = new HashMap<String, String>();
models.put("username", "XXX");
models.put("code", "4551"); String text = StringUtils.replacePlaceHolder(htmlTemplate, models); // 2. send email
boolean result = mailHandler.sendText("收件人邮箱", "发送带模板数据的Email", text);
Assert.assertEquals(true, result);

二、使用Velocity模板

  实现方法:借用VelocityEngineUtils合并Velocity模板和数据,得到要发送的Email, 进行发送。

1) 引入依赖jar包

<!-- velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

2) 配置Velocity模板引擎

<!-- Define velocity engine -->
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="configLocation" value="classpath:velocity.properties" />
</bean>
velocity.properties:
input.encoding=UTF-8
output.encoding=UTF-8
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

3) 发送邮件实现函数

// Get email content by velocity merge models
String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, encoding, models); // Send email
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, encoding);
helper.setFrom(form); // set sender
helper.setTo(to); // set recipients
helper.setSubject(subject);
helper.setText(content, true); // Indicate the text included is HTML
mailSender.send(mimeMessage);

三、使用FreeMarker模板

  实现方法:借用FreeMarkerTemplateUtils合并FreeMarker模板和数据,得到要发送的Email, 进行发送。

1) 引入依赖jar包

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
</dependency>

2)配置FreeMarker

<!-- Define freemarker configuration -->
<bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
  <property name="templateLoaderPath" value="classpath:template/freemarker" />
  <property name="defaultEncoding" value="utf-8" />
  <property name="freemarkerSettings">
  <props>
  <prop key="template_update_delay">10</prop>
  <prop key="locale">zh_CN</prop>
      <prop key="number_format">#.##</prop>
    </props>
  </property>
</bean>

3) 发送邮件实现函数

// Get email content by freeMarker template
Template realTemplate = freeMarkerConfigurer.getTemplate(template);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(realTemplate, models);
// Send email
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, encoding);
helper.setFrom(form); // set sender
helper.setTo(to); // set recipients
helper.setSubject(subject);
helper.setText(content, true); // Indicate the text included is HTML
mailSender.send(mimeMessage);

Spring邮件发送2的更多相关文章

  1. Spring 邮件发送

      前言:以前都是直接用Java自带的邮件工具发送邮件,现在Spring帮我们做了封装,提供了更好用更简单的发送邮件工具JavaMailSender 关于邮件服务器的设置就不在这里说了,直接去QQ邮箱 ...

  2. java spring 邮件发送

    开发中经常会遇到发送邮件进行用户验证,或者其它推送信息的情况,本文基于spring,完成邮件的发送,主要支持普通文本邮件的发送,html文本邮件的发送,带附件的邮件发送,没有实现群发.多个附件发送等需 ...

  3. Spring邮件发送1

    注意:邮件发送code中,邮件服务器的申请和配置是比较主要的一个环节,博主这里用的是QQ的邮件服务器.有需要的可以谷歌.百度查下如何开通. 今天看了下Spring的官方文档的邮件发送这一章节.在这里记 ...

  4. spring邮件发送

    1,Emaill类: package com.learn.jsp.pojo; /** * 邮件基本信息 * @author kevin * */public class Email { private ...

  5. Spring的javaMail邮件发送(带附件)

    项目中经常用到邮件功能,在这里简单的做一下笔记,方便日后温习. 首先需要在配置文件jdbc.properties添加: #------------ Mail ------------ mail.smt ...

  6. 使用spring的邮件发送功能

    使用spring提供的MailSender和JavaMailSender类. 1.邮件对象类 package cn.luxh.app.mail; import java.util.List; impo ...

  7. 使用Spring的JAVA Mail支持简化邮件发送(转)

    闲来无事,翻看<Spring in Action>,发现Spring集成了对JAVA Mail的支持,有点小激动的看了一遍,嗯,话说真的简单了很多. Spring的邮件发送的核心是Mail ...

  8. Spring Boot 2.0 图文教程 | 集成邮件发送功能

    文章首发自个人微信公众号: 小哈学Java 个人网站: https://www.exception.site/springboot/spring-boots-send-mail 大家好,后续会间断地奉 ...

  9. Spring Boot整合邮件发送

    概述 Spring Boot下面整合了邮件服务器,使用Spring Boot能够轻松实现邮件发送:整理下最近使用Spring Boot发送邮件和注意事项: Maven包依赖 <dependenc ...

随机推荐

  1. 软件测试必备-前端知识点之html基础

    前端必备知识点 第一部分:HTML基础 一. web前端标准 1. 结构标签----html 2. 样式标准,美化----css 3. 行为标准---js 二. 五大浏览器厂商 1. ie 2. 谷歌 ...

  2. MyBatis映射器元素

     映射器是MyBatis最强大的工具,也是我们使用MyBatis时用的最多的工具,映射器中主要有增删改查四大元素,来满足不同场景的需要: 下面是主要元素的介绍:         select:查询语句 ...

  3. python数据类型:序列(字符串,元组,列表,字典)

    序列通常有2个特点: 1,可以根据索引取值 2,可以切片操作 字符串,元组,列表,字典,都可以看做是序列类型 我的操作环境:Ubuntu16.04+python2.7 一.字符串类型 >按索引获 ...

  4. SDN资料

    深入浅出SDN 华为SDN PPT 基于分类的软件定义网络流表更新一致性方案 SDN-网络变革的探讨 Openflow交换机初步安装测试 floodlight源码解读. Floodlight核心包源码 ...

  5. iOS 神秘而又强大的传感器系统 (附demo)

    iOS中的各种传感器: 随着科技的发展,机器感知人的行为!Goole的无人驾驶汽车到李彦宏的无人驾汽车,都带入了各种计算及传感. 为了研究自然现象和制造劳动工具,人类必须了解外界的各类信息.了解外界信 ...

  6. 记录解决python在spark运行加载第三方库的问题

    一般写python的我们经常会import一些常用的库,然后有时集群环境上的python没有这些库,怎么办呢? 通过一段时间的摸索发现有二种方式可以解决这个问题: 第一种方法: 下载对应python的 ...

  7. python爬微信公众号前10篇历史文章(1)-思路概览

    作为程序员,要时刻保持一颗好奇心和想要学习的姿态. 练习怎样利用搜狗微信爬取某指定微信公众号的历史文章.爬取微信公众号本身难度非常大,感谢搜狗提供了一个可以爬取数据的平台. 代码部分参考于: http ...

  8. 关于脱离laravel框架使用Illuminate/Validation验证器

    1.关于Illuminate/Validation验证器 Validation 类用于验证数据以及获取错误消息. github地址:github.com/illuminate/validation 文 ...

  9. Python 中 mySQL 中的语句

    class DeleteInventorybusiness(BaseBusiness): def DeleteInventory(self,Delete_goodsID): DeleteInvento ...

  10. iOS scrollView中嵌套多个tabeleView处理方案

    项目中经常会有这样的需求,scrollView有个头部,当scrollView滚动的时候头部也跟着滚动,同时头部还有一个tab会锁定在某个位置,scrollView中可以放很多不同的view,这些vi ...