Creating email content using a templating library

The code in the previous examples explicitly created the content of the email message, using methods calls such as message.setText(..). This is fine for simple cases, and it is okay in the context of the aforementioned examples, where the intent was to show you the very basics of the API.

In your typical enterprise application though, you are not going to create the content of your emails using the above approach for a number of reasons.

  • Creating HTML-based email content in Java code is tedious and error prone
  • There is no clear separation between display logic and business logic
  • Changing the display structure of the email content requires writing Java code, recompiling, redeploying…​

Typically the approach taken to address these issues is to use a template library such as FreeMarker or Velocity to define the display structure of email content. This leaves your code tasked only with creating the data that is to be rendered in the email template and sending the email. It is definitely a best practice for when the content of your emails becomes even moderately complex, and with the Spring Framework’s support classes for FreeMarker and Velocity becomes quite easy to do. Find below an example of using the Velocity template library to create email content.

A Velocity-based example

To use Velocity to create your email template(s), you will need to have the Velocity libraries available on your classpath. You will also need to create one or more Velocity templates for the email content that your application needs. Find below the Velocity template that this example will be using. As you can see it is HTML-based, and since it is plain text it can be created using your favorite HTML or text editor.

# in the com/foo/package
<html>
<body>
<h3>Hi ${user.userName}, welcome to the Chipping Sodbury On-the-Hill message boards!</h3> <div>
Your email address is <a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.
</div>
</body>
</html>

Find below some simple code and Spring XML configuration that makes use of the above Velocity template to create email content and send email(s).

package com.foo;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils; import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map; public class SimpleRegistrationService implements RegistrationService { private JavaMailSender mailSender;
private VelocityEngine velocityEngine; public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
} public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
} public void register(User user) { // Do the registration logic... sendConfirmationEmail(user);
} private void sendConfirmationEmail(final User user) {
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(user.getEmailAddress());
message.setFrom("webmaster@csonth.gov.uk"); // could be parameterized...
Map model = new HashMap();
model.put("user", user);
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "com/dns/registration-confirmation.vm", model);
message.setText(text, true);
}
};
this.mailSender.send(preparator);
} }
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.csonth.gov.uk"/>
</bean> <bean id="registrationService" class="com.foo.SimpleRegistrationService">
<property name="mailSender" ref="mailSender"/>
<property name="velocityEngine" ref="velocityEngine"/>
</bean> <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean> </beans> 附录:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

  

模板发送java邮件的更多相关文章

  1. flask 电子邮件进阶实践-用模板发送163邮件

    电子邮件进阶实践 下面来学习构建邮件的HTML正文,并使用模板组织内容. 一封电子邮件的正文可以是纯文本(text/plain),也可以是HTML格式的文本(text/html).处于全面的考虑,一封 ...

  2. SpringBoot集成Thymeleaf发送Html邮件报错

    由于业务需求需要使用Thymeleaf作为模板发送Html邮件,开发调试过程中发生以下错误 org.thymeleaf.exceptions.TemplateInputException: Error ...

  3. java邮件发送(含附件)

    1. [代码]java邮件发送(含附件)疯狂的IT人站长整理的:利用Java发送邮件(含附件)的例子:1.邮件发送的配置propertity文件内容如下:(utils.properties文件放在sr ...

  4. Java邮件发送与接收原理

    一. 邮件开发涉及到的一些基本概念 1.1.邮件服务器和电子邮箱 要在Internet上提供电子邮件功能,必须有专门的电子邮件服务器.例如现在Internet很多提供邮件服务的厂商:sina.sohu ...

  5. Java 邮件发送

    <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId&g ...

  6. 【Java EE 学习 21 下】【使用java实现邮件发送、邮件验证】

    一.邮件发送 1.邮件发送使用SMTP协议或者IMAP协议,这里使用SMTP协议演示. SMTP协议使用的端口号:25 rfc821详细记载了该协议的相关信息 (1)使用telnet发送邮件(使用12 ...

  7. JAVA邮件发送的简单实现

    JAVA MAIL是利用现有的邮件账户发送邮件的工具,比如说,我在网易注册一个邮箱账户,通过JAVA Mail的操控,我可以不亲自登录网易邮箱,让程序自动的使用网易邮箱发送邮件.这一机制被广泛的用在注 ...

  8. java邮件发送 qq与163邮箱互发和qq和163邮箱发送其他邮箱实例

    研究了近一天的时间,通过查阅相关资料,终于对java发送邮件的机制,原理有了一点点的理解,希望能够帮到大家! 1.首先要向你的项目里导入1个jar包:mail-1.4.4.jar即可(实现qq和163 ...

  9. .net邮件发送实例 邮件内容为网页模板

    .net邮件发送实例 邮件内容为网页模板 2009-07-03 09:31:01|  分类: .NET|字号 订阅      Encoding encoding = Encoding.GetEncod ...

随机推荐

  1. 【JAVA】学习笔记(2)

    Java完整的类的定义 [pubilc][abstact|final] class className [extends superclassName] [implements InterfaceNa ...

  2. 移动端常见bug

    meta基础知识 H5页面窗口自动调整到设备宽度,并禁止用户缩放页面 <meta name="viewport" content="width=device-wid ...

  3. JupyterLab绘制:柱状图,饼状图,直方图,散点图,折线图

    JupyterLab绘图 喜欢python的同学,可以到 https://v3u.cn/(刘悦的技术博客) 里面去看看,爬虫,数据库,flask,Django,机器学习,前端知识点,JavaScrip ...

  4. 关于Selenium.common.exceptions.WebDriverException: Message: Invalid locator strategy: css selector 的问题

    在执行脚本时报Selenium.common.exceptions.WebDriverException: Message: Invalid locator strategy: css selecto ...

  5. git使用之后悔药

    1.工作区的代码想撤销 背景:有时候编写了一大段代码之后,想要撤销更改(执行add操作之前), 命令:git checkout -- <file路径> 使用git checkout -- ...

  6. Android缩放动画[ScaleAnimation]

    @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); s ...

  7. bzoj4568(合并线性基+倍增)

    裸题练习模板 #include<iostream> #include<cstring> #include<cmath> #include<cstdio> ...

  8. c++实现对windwos 下socket 的封装(实现封包及拆包处理)

    SuperSocket.h #pragma once #include<string> #include<iostream> #include <WINSOCK2.H&g ...

  9. js-图片轮播(极简)

    <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" ...

  10. CS61A Lecture3 Note

    本次lec主讲控制流 本文档只列一些py控制流与C不同的地方  print的功能不同 可以print出来None这种东西 重点讲了函数运行机制,我的理解是这样的,在调用函数之前,def会产生一个glo ...