模板发送java邮件
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邮件的更多相关文章
- flask 电子邮件进阶实践-用模板发送163邮件
电子邮件进阶实践 下面来学习构建邮件的HTML正文,并使用模板组织内容. 一封电子邮件的正文可以是纯文本(text/plain),也可以是HTML格式的文本(text/html).处于全面的考虑,一封 ...
- SpringBoot集成Thymeleaf发送Html邮件报错
由于业务需求需要使用Thymeleaf作为模板发送Html邮件,开发调试过程中发生以下错误 org.thymeleaf.exceptions.TemplateInputException: Error ...
- java邮件发送(含附件)
1. [代码]java邮件发送(含附件)疯狂的IT人站长整理的:利用Java发送邮件(含附件)的例子:1.邮件发送的配置propertity文件内容如下:(utils.properties文件放在sr ...
- Java邮件发送与接收原理
一. 邮件开发涉及到的一些基本概念 1.1.邮件服务器和电子邮箱 要在Internet上提供电子邮件功能,必须有专门的电子邮件服务器.例如现在Internet很多提供邮件服务的厂商:sina.sohu ...
- Java 邮件发送
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId&g ...
- 【Java EE 学习 21 下】【使用java实现邮件发送、邮件验证】
一.邮件发送 1.邮件发送使用SMTP协议或者IMAP协议,这里使用SMTP协议演示. SMTP协议使用的端口号:25 rfc821详细记载了该协议的相关信息 (1)使用telnet发送邮件(使用12 ...
- JAVA邮件发送的简单实现
JAVA MAIL是利用现有的邮件账户发送邮件的工具,比如说,我在网易注册一个邮箱账户,通过JAVA Mail的操控,我可以不亲自登录网易邮箱,让程序自动的使用网易邮箱发送邮件.这一机制被广泛的用在注 ...
- java邮件发送 qq与163邮箱互发和qq和163邮箱发送其他邮箱实例
研究了近一天的时间,通过查阅相关资料,终于对java发送邮件的机制,原理有了一点点的理解,希望能够帮到大家! 1.首先要向你的项目里导入1个jar包:mail-1.4.4.jar即可(实现qq和163 ...
- .net邮件发送实例 邮件内容为网页模板
.net邮件发送实例 邮件内容为网页模板 2009-07-03 09:31:01| 分类: .NET|字号 订阅 Encoding encoding = Encoding.GetEncod ...
随机推荐
- 【机器学习】异常检测算法(I)
在给定的数据集,我们假设数据是正常的 ,现在需要知道新给的数据Xtest中不属于该组数据的几率p(X). 异常检测主要用来识别欺骗,例如通过之前的数据来识别新一次的数据是否存在异常,比如根据一个用户以 ...
- Tomcat 500error: Could not initialize class
Web 项目报错Could not initialize class ,出现500,说明服务器是起来了,可能是这个类的驱动有问题,缺少初始化需要的文件 查到有相关情况: 考虑是jar 包的问题,检查了 ...
- tensorflow学习之(十一)将python代码写入文件
#save to file import tensorflow as tf import numpy as np ##(1)Save to file 把相关变量存储到文件中 #remember to ...
- 数据结构与STL容器
1.静态数组 静态数组就是大小固定不能扩展的数组,如C中普通数组.C++11中array. 2.动态数组 动态数组的空间大小在需要的时候可以进行再分配,其代表为vector.由于数组的特点,在位置0插 ...
- istio实现自动sidecar自动注入(k8s1.13.3+istio1.1.1)
一.自动注入的前提条件 自动注入功能需要kubernetes 1.9或更高版本: kubernetes环境需支持MutatingAdmissionWebhook: 二.在namespace中设置自动注 ...
- [Solution] JZOJ-5818 做运动
[Solution] JZOJ-5818 做运动 Time Limits:2000ms Memory Limits:524288KB Description 一天,Y 君在测量体重的时候惊讶的发现,由 ...
- hadoop2.7集群安装
1. 按照官方文档对单节点的配置,将etc/hadoop/core-site.xml中的localhost改成node13. http://hadoop.apache.org/docs/r2.7.3/ ...
- noip第22课资料
- Android 极光推送造成IM服务绑定失败bug
由于极光推送对8.0的支持问题,升级到了最新版本的极光推送.但是最新版本的极光推送,默认将推送服务设置到了新的进程里面,由此引发 Android 极光推送多进程造成的application运行两次 和 ...
- Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)
本人编程小白,如果有写的不对.或者能更完善的地方请个位批评指正! 这个是leetcode的第34题,这道题的tag是数组,需要用到二分搜索法来解答 34. Find First and Last Po ...