java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html、velocity模板
本文主要介绍利用JavaMailSenderImpl发送邮件。首先介绍了发送一般邮件,然后介绍了发送富文本(html)邮件及以velocity为模板发送邮件。
邮件发送分为为三步:创建邮件发送器、编写邮件、发送邮件。
Spring的JavaMailSenderImpl提供了强大的邮件发送功能,可发送普通文本邮件、带附件邮件、html格式邮件、带图片邮件、设置发送内容编码格式、设置发送人的显示名称。
下面就进行介绍,示例代码中很多都是字符串硬编码,实际使用时推荐使用spring的配置文件进行配置。
1、创建邮件发送器
首先定义JavaMailSenderImpl对象,并对其进行smtp相关信息设置,相当于我们自己的邮箱,如下:
- JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
- mailSender.setHost("smtp.qq.com");
- mailSender.setUsername("mosaic@qq.com");
- mailSender.setPassword("asterisks");
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.qq.com");
mailSender.setUsername("mosaic@qq.com");
mailSender.setPassword("asterisks");
当然更好的方法是使用配置文件进行配置,这里只是进行介绍,忽略硬编码先。
以上主机为邮箱服务商的smtp地址,用户名、密码为用户自己的邮箱。除以上外还可以设置
setPort(int port) 、setProtocol(String protocol) 等,可暂时不考虑。
这样我们便类似创建好了一个邮件发送器
2、 开始写邮件,编写邮件内容
JavaMailSenderImpl支持MimeMessages和
SimpleMailMessages。
MimeMessages为复杂邮件模板,支持文本、附件、html、图片等。
SimpleMailMessages实现了MimeMessageHelper,为普通邮件模板,支持文本。
下面先以SimpleMailMessages为例进行介绍
- SimpleMailMessage smm = new SimpleMailMessage();
- // 设定邮件参数
- smm.setFrom(mailSender.getUsername());
- smm.setTo("mosaic@126.com");
- smm.setSubject("Hello world");
- smm.setText("Hello world via spring mail sender");
- // 发送邮件
- mailSender.send(smm);
SimpleMailMessage smm = new SimpleMailMessage();
// 设定邮件参数
smm.setFrom(mailSender.getUsername());
smm.setTo("mosaic@126.com");
smm.setSubject("Hello world");
smm.setText("Hello world via spring mail sender");
// 发送邮件
mailSender.send(smm);
如此,我们便完成了一个简单邮件的编写,对于复杂邮件,编写及发送如下
- //使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容
- MimeMessage msg = mailSender.createMimeMessage();
- //创建MimeMessageHelper对象,处理MimeMessage的辅助类
- MimeMessageHelper helper = new MimeMessageHelper(msg, true);
- //使用辅助类MimeMessage设定参数
- helper.setFrom(mailSender.getUsername());
- helper.setTo("mosaic@126.com");
- helper.setSubject("Hello Attachment");
- helper.setText("This is a mail with attachment");
- //加载文件资源,作为附件
- ClassPathResource file = new ClassPathResource("Chrysanthemum.jpg");
- //加入附件
- helper.addAttachment("attachment.jpg", file);
- // 发送邮件
- mailSender.send(smm);
//使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容
MimeMessage msg = mailSender.createMimeMessage();
//创建MimeMessageHelper对象,处理MimeMessage的辅助类
MimeMessageHelper helper = new MimeMessageHelper(msg, true);
//使用辅助类MimeMessage设定参数
helper.setFrom(mailSender.getUsername());
helper.setTo("mosaic@126.com");
helper.setSubject("Hello Attachment");
helper.setText("This is a mail with attachment");
//加载文件资源,作为附件
ClassPathResource file = new ClassPathResource("Chrysanthemum.jpg");
//加入附件
helper.addAttachment("attachment.jpg", file);
// 发送邮件
mailSender.send(smm);
其中MimeMessageHelper为的辅助类MimeMessages。以上包含了以资源文件为附件进行发送。对于普通文件发送方式如下:
- FileSystemResource file = new FileSystemResource("C:\\Users\\image1.jpg");
- helper.addInline("file", file);
FileSystemResource file = new FileSystemResource("C:\\Users\\image1.jpg");
helper.addInline("file", file);
3、发送邮件
2中已经包含了发送的代码,只需使用JavaMailSenderImpl的send接口即可。支持类型为
- void send(MimeMessage mimeMessage)
- Send the given JavaMail MIME message.
- void send(MimeMessage[] mimeMessages)
- Send the given array of JavaMail MIME messages in batch.
- void send(MimeMessagePreparator mimeMessagePreparator)
- Send the JavaMail MIME message prepared by the given MimeMessagePreparator.
- void send(MimeMessagePreparator[] mimeMessagePreparators)
- Send the JavaMail MIME messages prepared by the given MimeMessagePreparators.
- void send(SimpleMailMessage simpleMessage)
- Send the given simple mail message.
- void send(SimpleMailMessage[] simpleMessages)
- Send the given array of simple mail messages in batch.
void send(MimeMessage mimeMessage)
Send the given JavaMail MIME message.
void send(MimeMessage[] mimeMessages)
Send the given array of JavaMail MIME messages in batch.
void send(MimeMessagePreparator mimeMessagePreparator)
Send the JavaMail MIME message prepared by the given MimeMessagePreparator.
void send(MimeMessagePreparator[] mimeMessagePreparators)
Send the JavaMail MIME messages prepared by the given MimeMessagePreparators.
void send(SimpleMailMessage simpleMessage)
Send the given simple mail message.
void send(SimpleMailMessage[] simpleMessages)
Send the given array of simple mail messages in batch.
下面介绍下怎么发送富文本文件以及以velocity为模板发送邮件。
4、发送html文件
只需要在MimeMessageHelper setText时将是否是html设为true即可。setText介绍如下:
- setText(String text, boolean html)
- Set the given text directly as content in non-multipart mode or as default body part in multipart mode.
setText(String text, boolean html)
Set the given text directly as content in non-multipart mode or as default body part in multipart mode.
示例代码(包括附件)如下:
- //第二个参数true,表示text的内容为html
- //注意<img/>标签,src='cid:file','cid'是contentId的缩写,'file'是一个标记,需要在后面的代码中调用MimeMessageHelper的addInline方法替代成文件
- helper.setText("<body><p>Hello Html Email</p><img src='cid:file'/></body>", true);
- FileSystemResource file = new FileSystemResource("C:\\Users\\image1.jpg");
- helper.addInline("file", file);
//第二个参数true,表示text的内容为html
//注意<img/>标签,src='cid:file','cid'是contentId的缩写,'file'是一个标记,需要在后面的代码中调用MimeMessageHelper的addInline方法替代成文件
helper.setText("<body><p>Hello Html Email</p><img src='cid:file'/></body>", true);
FileSystemResource file = new FileSystemResource("C:\\Users\\image1.jpg");
helper.addInline("file", file);
5、以velocity为模板发送邮件
使用Velocity模板,需要Velocity的jar包,可以在官方网站下载,并加入ClassPath。
以velocity为模板发送邮件的原理如下:
a 类似web编程,将velocity作为前端,在java中设置vm中需要显示的变量值
b 使用VelocityEngineUtils的mergeTemplateIntoString函数将vm内容转换为文本
c 同4的发送html邮件一样发送邮件
所以最重要的过程将是将vm的内容转换为string,即设置邮件内容,其他同上面并无差异
5.1 新建vm文件,命名为index.vm
- <html>
- <head>
- </head>
- <body>
- <div>${user} </div>
- <div>${content}</div>
- </body>
- </html><SPAN style="BACKGROUND-COLOR: #ffffff; WHITE-SPACE: normal"> </SPAN>
<html>
<head>
</head>
<body>
<div>${user} </div>
<div>${content}</div>
</body>
</html>
为了方便省略了html头定义。
其中${user} 为Velocity的语法,相当于一个变量,在java程序中可以设置这个变量的值在前端显示。
5.2 创建VelocityEngineFactoryBean对象,并设置属性
- // Velocity的参数,通过VelocityEngineFactoryBean创建VelocityEngine,也是推荐在配置文件中配置的
- Properties properties = System.getProperties();
- properties.put("resource.loader", "class");
- properties.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
- VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();
- v.setVelocityProperties(properties);
// Velocity的参数,通过VelocityEngineFactoryBean创建VelocityEngine,也是推荐在配置文件中配置的
Properties properties = System.getProperties();
properties.put("resource.loader", "class");
properties.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();
v.setVelocityProperties(properties);
5.3 转换vm内容为普通String
- // 声明Map对象,并填入用来填充模板文件的键值对
- Map<String, String> model = new HashMap<String, String>();
- model.put("user", "ooo");
- model.put("content", "nihao");
- // Spring提供的VelocityEngineUtils将模板进行数据填充,并转换成普通的String对象
- String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "index.vm", model);
// 声明Map对象,并填入用来填充模板文件的键值对
Map<String, String> model = new HashMap<String, String>();
model.put("user", "ooo");
model.put("content", "nihao");
// Spring提供的VelocityEngineUtils将模板进行数据填充,并转换成普通的String对象
String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "index.vm", model);
这样我们便将vm中的变量值填充好,并且将内容转换为了string
5.4 设置邮件内容,同4
- helper.setText(emailText, true);
helper.setText(emailText, true);
其他内容同上面的1、2、3过程。
注意:vm文件格式需要与邮件编码一致否则会出现乱码
java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html、velocity模板的更多相关文章
- 利用spring boot创建java app
利用spring boot创建java app 背景 在使用spring框架开发的过程中,随着功能以及业务逻辑的日益复杂,应用伴随着大量的XML配置和复杂的bean依赖关系,特别是在使用mvc的时候各 ...
- Java RMI 介绍和例子以及Spring对RMI支持的实际应用实例
RMI 相关知识 RMI全称是Remote Method Invocation-远程方法调用,Java RMI在JDK1.1中实现的,其威力就体现在它强大的开发分布式网络应用的能力上,是纯Java的网 ...
- [Java][web]利用Spring随时随地获得Request和Session
利用Spring随时随地获得Request和Session 一.准备工作: 在web.xml中加入 <listener> <listener-class> org.spring ...
- 利用java从docx文档中提取文本内容
利用java从docx文档中提取文本内容 使用Apache的第三方jar包,地址为https://poi.apache.org/ docx文档内容如图: 目录结构: 每个文件夹的名称为日期加上来源,例 ...
- 47. Spring Boot发送邮件【从零开始学Spring Boot】
(提供源代码) Spring提供了非常好用的JavaMailSender接口实现邮件发送.在Spring Boot的Starter模块中也为此提供了自动化配置.下面通过实例看看如何在Spring Bo ...
- Java 学习(18):Java 序列化& 网络编程& 发送邮件
--Java 序列化 -- 网络编程 -- 发送邮件 Java 序列化 Java 提供了一种对象序列化的机制,该机制中,一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据.有关对象的类型的信 ...
- [Java] 使用 Spring 2 Portlet MVC 框架构建 Portlet 应用
转自:http://www.ibm.com/developerworks/cn/java/j-lo-spring2-portal/ Spring 除了支持传统的基于 Servlet 的 Web 开发之 ...
- 利用Spring AOP自定义注解解决日志和签名校验
转载:http://www.cnblogs.com/shipengzhi/articles/2716004.html 一.需解决的问题 部分API有签名参数(signature),Passport首先 ...
- 利用Spring Cloud实现微服务- 熔断机制
1. 熔断机制介绍 在介绍熔断机制之前,我们需要了解微服务的雪崩效应.在微服务架构中,微服务是完成一个单一的业务功能,这样做的好处是可以做到解耦,每个微服务可以独立演进.但是,一个应用可能会有多个微服 ...
随机推荐
- winform的常用公共控件和常用属性
我们在学位winform的控件和属性的时候要学会赋值取值还有改值 公共控件: 1,Button(按钮): Enabled :是否可用 Visible:是否可见 2,CheckBox(多选项) Chec ...
- (转)建站知识:域名/ 空间/ IP/ 端口之间的关系
先说域名解析吧,比如说你的域名是 www.sunnymould.com,这个域名对应着一个IP地址,域名解析就是把上面的域名转换成这个IP地址的过程,这样你就可以域名访问了上面地址上的内容了. 端口映 ...
- [问题2014A12] 复旦高等代数 I(14级)每周一题(第十四教学周)
[问题2014A12] 设 \(A,B\) 是 \(n\) 阶方阵且满足 \(AB=BA=0\), \(\mathrm{r}(A)=\mathrm{r}(A^2)\), 证明: \[\mathrm{ ...
- 登录锁定状态下Win7关机技巧总结
登录锁定状态下Win7关机技巧总结 一般在锁定状态都是有个关闭电脑的图标的.但是如果你的系统没有,那么怎么样关机呢,所谓的锁定状态通常是指电脑在登录界面,具体的实现如下,感兴趣的朋友可以参考下 现在大 ...
- PHP中的闭包和匿名函数
闭包的概念是指在创建闭包时,闭包会封装周围的状态的函数.即便闭包所在环境不在了.但闭包中封装的状态依然存在. 匿名函数就是没有名称的函数. 它们看似很函数一样,实际上它们属于Closure类的实例 P ...
- 转{QQ浏览器X5内核问题汇总}
转自https://www.qianduan.net/qqliu-lan-qi-x5nei-he-wen-ti-hui-zong/ 常常被人问及微信中使用的X5内核的问题,其实我也不是很清楚,只知道它 ...
- js执行顺序<转>
JavaScript执行引擎并非一行一行地分析和执行程序,而是一段一段地分析执行的.而且在分析执行同一段代码中,定义式的函数语句会被提取出来优先执行.函数定义执行完后,才会按顺序执行其他代码. 先看看 ...
- table插件实现
选择.取消.全选.全部取消.获取行ids /** * Created by lizongqiong on 2016/1/8. */ var $ = require('jquery'); var tab ...
- Flyweight
1 意图:运用共享技术有效地大量支持细粒度的对象 2 动机:flyweight是一个共享对象,可以在多个场景使用. 分为内部状态和外部状态,内部状态存储于flyweight中,包含了独立于flywei ...
- php null o false ''
php中很多还不懂php中0,"",null和false之间的区别,这些区别有时会影响到数据判断的正确性和安全性,给程序的测试运行造成很多麻烦.先看一个例子: <? $str ...