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

一、解析自定义占位符

  实现方法: 通过解析自定义占位符,将传递到邮件中的数据,转换成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. IE浏览器右键菜单插件开发(下篇)——如何用c#安装、卸载IE右键插件

    建立Installer安装类,如图: 代码如下: using Microsoft.Win32; using ResourceShare.UserClient.Common; using System; ...

  2. IDEA 使用tomcat7-maven-plugin

    使用了这个插件就不需要配置tomcat了,直接用maven去run就行 配置方法:pom里添加:(之所以用tomcat7是因为如果直接用依赖下载很难下载到tomcat8-maven-plugin,详情 ...

  3. js备战春招の三

    DOM (Document Object Model)(文档对象模型)是用于访问 HTML 元素的正式 W3C 标准. window.alert() 弹出警告框. document.write() 方 ...

  4. 在Editplus中配置java的(带包)编译(javac)和运行(java)的方法

    配置的前提是电脑安装了JDK并且配置好了相关的环境变量(JAVA_HOME,path和classpath). 配置好后在命令行中输入javac和java验证是否配置成功: 如果出现上面的情况则说明配置 ...

  5. 深入浅出了解OCR识别票据原理(Applying OCR Technology for Receipt Recognition)

    原文:Applying OCR Technology for Receipt Recognition 译文:深入浅出了解OCR识别票据原理 英文票据识别技术, 非中文票据识别技术, 中文情况的ocr更 ...

  6. JQ 判断 浏览器打开的设备类型

    <script> $(document).ready(function(){ var ua = navigator.userAgent; var ipad = ua.match(/(iPa ...

  7. RxJS速成 (上)

    What is RxJS? RxJS是ReactiveX编程理念的JavaScript版本.ReactiveX是一种针对异步数据流的编程.简单来说,它将一切数据,包括HTTP请求,DOM事件或者普通数 ...

  8. java-线程实现方式

    实现方式: 1,继承Thread类 public class ThreadTest extends Thread { @Override public void run() { System.out. ...

  9. 数据库 --> MySQL使用

    MySQL使用 代码: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>#includ ...

  10. Java ORM Hibernate 入门笔记

    一.下载 官网地址:http://hibernate.org/ Hibernate下有ORM(关系型数据库).OGM(NoSQL数据库).Search(对象全文检索).Validator的工具. OR ...