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

一、解析自定义占位符

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

1)占位符替换函数

  1. /**
  2. * Replaces place holder ("${}") string in template with values in Map
  3. *
  4. * @param template
  5. * @param models
  6. * @return
  7. */
  8. public static String replacePlaceHolder(String template, Map<String, String> models) {
  9.  
  10. if (template.indexOf("${") == -1) {
  11. return template;
  12. }
  13.  
  14. while (true) {
  15.  
  16. int start = template.indexOf("${");
  17. int end = template.indexOf("}", start);
  18.  
  19. if (start != -1 && end != -1) {
  20.  
  21. String key = template.substring(start + 2, end);
  22.  
  23. if (models.containsKey(key)) {
  24. template = template.substring(0, start) + models.get(key) + template.substring(end + 1);
  25. }
  26.  
  27. } else {
  28. break;
  29. }
  30.  
  31. }
  32.  
  33. return template;
  34.  
  35. }

2) 邮件发送Test-Case

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

二、使用Velocity模板

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

1) 引入依赖jar包

  1. <!-- velocity -->
  2. <dependency>
  3. <groupId>org.apache.velocity</groupId>
  4. <artifactId>velocity</artifactId>
  5. <version>1.7</version>
  6. </dependency>

2) 配置Velocity模板引擎

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

3) 发送邮件实现函数

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

三、使用FreeMarker模板

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

1) 引入依赖jar包

  1. <dependency>
  2.   <groupId>org.freemarker</groupId>
  3.   <artifactId>freemarker</artifactId>
  4.   <version>2.3.23</version>
  5. </dependency>

2)配置FreeMarker

  1. <!-- Define freemarker configuration -->
  2. <bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
  3.   <property name="templateLoaderPath" value="classpath:template/freemarker" />
  4.   <property name="defaultEncoding" value="utf-8" />
  5.   <property name="freemarkerSettings">
  6.   <props>
  7.   <prop key="template_update_delay">10</prop>
  8.   <prop key="locale">zh_CN</prop>
  9.       <prop key="number_format">#.##</prop>
  10.     </props>
  11.   </property>
  12. </bean>

3) 发送邮件实现函数

  1. // Get email content by freeMarker template
    Template realTemplate = freeMarkerConfigurer.getTemplate(template);
  2. String content = FreeMarkerTemplateUtils.processTemplateIntoString(realTemplate, models);
  1. // Send email
  2. MimeMessage mimeMessage = mailSender.createMimeMessage();
  3. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, encoding);
  4. helper.setFrom(form); // set sender
  5. helper.setTo(to); // set recipients
  6. helper.setSubject(subject);
  7. helper.setText(content, true); // Indicate the text included is HTML
  8. 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. Dapper一个和petapoco差不多的轻量级ORM框架

    我们都知道ORM全称叫做Object Relationship Mapper,也就是可以用object来map我们的db,而且市面上的orm框架有很多,其中有一个框架 叫做dapper,而且被称为th ...

  2. angular路由详解一(基础知识)

    本人原来是iOS开发,没想到工作后,离iOS开发原来越远,走上了前端的坑.一路走来,也没有向别人一样遇到一个技术上的师傅,无奈只能一个人苦苦摸索.如今又开始填angular的坑了.闲话不扯了.(本人学 ...

  3. Tencent研发工程师笔试知识点

      一: 32位编译器:32位系统下指针占用4字节       char :1个字节       char*(即指针变量): 4个字节(32位的寻址空间是2^32, 即32个bit,也就是4个字节.同 ...

  4. Linux环境下jdk1.8压缩包下载

    jdk1.8下载: 百度云链接:https://pan.baidu.com/s/1c37VcPi 密码:e6qh

  5. jdk7u79linuxx64.tar.gz下载

    jdk1.7下载: 百度云盘链接:https://pan.baidu.com/s/1cQFLnS 密码:wdek

  6. spark source code 分析之ApplicationMaster overview(yarn deploy client mode)

    一直不是很清楚ApplicationMaster的作用,尤其是在yarn client mode和cluster mode的区别 网上有一些非常好的资料,请移步: https://blog.cloud ...

  7. centos6.x上安装Java-1.8.0

    author : headsen chen date : 2017-12-04  10:32:44 notice :This  article is created by headsen chen h ...

  8. python学习-字符串前面添加u,r,b的含义

    引用:https://www.cnblogs.com/cq90/p/6959567.html u/U:表示unicode字符串 不是仅仅是针对中文, 可以针对任何的字符串,代表是对字符串进行unico ...

  9. JS面向对象与面向过程

    前言 面向对象编程: 就是将你的需求抽象成一个对象,然后针对这个对象分析其特征(属性)与动作(方法)--这个对象就称之为类 面向过程编程: 特点:封装,就是将你需要的功能放在一个对象里面 ------ ...

  10. day1 安装jdk8环境及第一个java程序

    安装jdk8 第一步:下载jdk安装包,我们这里下载orical官网的jdk8版本.