使用javaMail和velocity来发送模板邮件

时间:2021-10-11 20:50:23

之前在ssh项目中有用过javaMail和velocity来发送邮件,实现的效果如下所示。

使用javaMail和velocity来发送模板邮件

这类邮件主要用于公司的推广宣传,比如商城的促销等场景。

今天打算将邮件模块也集成到ssm项目,也算是对之前做的东西的一种巩固。

简单邮件模块

首先来集成简单的邮件模块。

1.第一步,加jar包,在maven的pom.xml加入如下代码。

<!-- 邮件 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>smtp</artifactId>
<version>1.6.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>mailapi</artifactId>
<version>1.6.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

2.编写mail.properties配置文件

#邮箱参数配置
mail.host:smtp.qq.com
mail.port:25
mail.username:xxxxx
mail.password:xxxxxx

3.在spring主配置文件中引入此配置文件

<!-- 读取properties文件 参数配置,所有的参数配置均可放在此处 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:mail.properties</value>
</list>
</property>
</bean>

4.新建spring-mail.xml文件,用于配置邮件相关的内容。

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="port" value="${mail.port}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
</beans>

5.在主配置文件中引入spring-mail.xml配置文件。

<import resource="spring-mail.xml" />

6.在一个controller类中编码调用邮件,注意需要注入mailSender这个bean.

    @Resource(name = "mailSender")
private JavaMailSender mailSender;
@ResponseBody
@RequestMapping(value = "simpleMailDemo", produces = "text/html; charset=utf-8")
public String simpleMailDemo() {
SimpleMailMessage mail = new SimpleMailMessage();
JavaMailSenderImpl mailSenderImpl = (JavaMailSenderImpl) mailSender;
// 发送方
mail.setFrom(mailSenderImpl.getUsername());
// 接收方
mail.setTo("2717814812@qq.com");
// 标题
mail.setSubject("spring mvc简单邮件发送");
// 设置邮件正文
mail.setText("spring mvc简单邮件发送,收到此邮件表明邮件模块配置成功");
mailSender.send(mail);
return "成功";
}

7.在浏览器输入http://192.168.1.185:8080/warrior/simpleMailDemo,结果如图。

使用javaMail和velocity来发送模板邮件

看看邮箱,确实收到了邮件。

使用javaMail和velocity来发送模板邮件

 采用velocity模板编写富文本邮件

1.第一步,引入velocity所需要用到的jar文件。

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

2.在spring-mail.xml中加入关于velocity的配置。

    <bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/templates/" /><!--
模板存放的路径 -->
<property name="configLocation" value="classpath:velocity.properties" />
</bean>
<!--配置试图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="false" />
<property name="prefix" value="" />
<property name="suffix" value=".vm" />
<property name="contentType" value="text/html;charset=utf-8" />
<property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="allowSessionOverride" value="true" />
<property name="allowRequestOverride" value="true" />
</bean>

注意上述配置我们将velocity的模板存在了web-inf下的templates文件夹下,并且启用了toolbox.xml配置,toolbox.xml主要是一些工具,你可以把你在编写velocity模板的时候可能会用到的工具填写到toolbox.xml中。

3.注意上述配置文件引入了velocity.properties文件,在resources下新建velocity.properties文件。

input.encoding=UTF-8
output.encoding=UTF-8

4.在web-inf下新建templates文件夹,新建toolbox.xml,此处我随便写了两个工具到toolbox.xml里面。

<?xml version="1.0" encoding="UTF-8" ?>
<toolbox>
<tool>
<key>UrlUtil</key>
<class>com.nali.common.util.UrlUtil</class>
<scope>application</scope>
</tool>
<tool>
<key>VersionUtil</key>
<class>com.ximalaya.shop.api.domain.util.VersionUtil</class>
<scope>application</scope>
</tool>
</toolbox>

4.编写velocity模板,在templates文件夹下面新建一个名为test.vm的模板。

<html>
<table style="display:none"><tr><td>逸品商城,优质农产品直供平台,会员专享,按需定制,个性化定产品,大宗商品,会员卡,宅配卡,逸品资讯,营养师服务,逸品云创亲子体验馆|WONYEN.COM</td></tr></table>
<table align="center" cellpadding="0" cellspacing="0" style="width:720px;border:0px;background-color:White;margin:0 auto;padding:10px 0px 0px 0px;">
<tbody>
<tr>
<td style="width:720px;height:40px;">
<table style="width:720px;height:40px;">
<tbody>
<tr>
<td style="width:130px;vertical-align:top;">
<a href="http://www.wonyen.com" target="_blank"><img src="http://wonyen.com/Images/logo_mail.png" border="0" width="160" height="40"></a>
</td>
<td style="width:230px;"></td>
<td style="width:90px;text-align:center;">
<a href="http://wonyen.com/" target="_blank" style="text-decoration:none;color:#333333;font-size:12pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif">首页</a>
</td>
<td style="width:90px;text-align:center;">
<a href="http://wonyen.com/yipinNews_All" target="_blank" style="text-decoration:none;color:#333333;font-size:12pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif">逸品资讯®</a>
</td>
<td style="width:90px;text-align:center;">
<a href="http://bbs.wonyen.com/" target="_blank" style="text-decoration:none;color:#333333;font-size:12pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif">会员社区 </a>
</td> <td style="width:90px;text-align:center;">
<a href="http://wonyen.com/yipinStreet" target="_blank" style="text-decoration:none;color:#333333;font-size:12pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif">逸品街 </a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="height: 15px;"></tr>
<tr>
<td style="height: 40px;color: #282828;font-size: 16pt;font-weight: 700;">
逸品<span style="color: #f6531a;">资讯®</span>
</td>
</tr>
<!--产品列表-->
#foreach($product in $productList)
<tr>
<td style="width:720px;height:100px;padding:20px 0px 15px 0px;border-bottom-color: #ccc;border-bottom-width: 1px;border-bottom-style: dotted;">
<table style="width:720px;">
<tbody>
<tr>
<td rowspan="2" style="width:138.9px;">
<a href="http://www.qgranite.com/productDetail?productId=$product.productId" target="_blank"><img style="border: 1px solid #ddd;" src="http://www.qgranite.com/$product.productPic" border="0" width="138.9" height="100"></a>
</td>
<td style="width:570px;height:20px;padding-left:10px;">
<a href="http://www.qgranite.com/productDetail?productId=$product.productId" target="_blank" style="font-weight:700;text-decoration:none;color:black;font-size:13pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif;">$product.productName</a>
</td>
</tr>
<tr>
<td style="width:570px;height:80px;padding-left:10px;line-height:25px;font-size:11pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif;color:#333333;">$product.description</td>
</tr>
</tbody>
</table>
</td>
</tr>
#end <tr>
<td>
<table>
<tbody>
<tr>
<td style="width:360px;height:20px;text-align:center;padding:0px 0px 0px 0px;font-size:9pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif;">
<table style="width:360px;">
<tbody>
<tr>
<td style="padding: 20px;text-align: center;">
<a href="http://www.wonyen.com/" target="_blank"><img style="width: 100px;height: 100px;" src="http://wonyen.com/Images/qrcode_for_wonyen_258.jpg" border="0"></a>
<a href="http://www.wonyen.com/" target="_blank"><img style="width: 100px;height: 100px;" src="http://wonyen.com/Images/qrcode_for_ifncn_258.jpg" border="0"></a>
</td>
</tr>
<tr>
<td style="font-size: 14px;text-align: center;">扫一扫,关注逸品商城微信公众号、订阅号</td>
</tr>
</tbody>
</table>
</td>
<td style="width:360px;height:20px;text-align:center;padding:0px 0px 0px 0px;font-size:9pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif;">
<table style="width:360px;">
<tbody>
<tr>
<td style="padding: 20px;text-align: center;">
<a href="http://www.wonyen.com/" target="_blank"><img style="height: 100px;" src="http://wonyen.com/Images/wechat_foot_img.png" border="0"></a>
</td>
</tr>
<tr>
<td style="font-size: 14px;">逸品商城---逸同分享 品质生活</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="height: 10px;"></tr>
<tr>
<td style="width:720px;height:23px;text-align:center;padding:0px 0px 5px 0px;font-size:9pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif;"><img style="height: 45px;" src="http://www.wonyen.com/Images/logo_mail_gray.png" border="0"></td>
</tr>
<tr style="height: 5px;"></tr>
<tr>
<td style="width:720px;height:20px;text-align:center;padding:0px 0px 30px 0px;font-size:9pt;font-family:'微软雅黑',Arial,Helvetica,sans-serif;">文逸科技 版权所有 Copyright © 2016 闽ICP备06033317号 </td>
</tr>
</tbody>
</table>
</html>

模板的编写与html文件类似,还可以试用循环。仔细看上述内容就可以发现。

5.最后,我们编写一个controller的方法来实现发送富文本邮件。

package com.xdx.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage; import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.xdx.entity.TProduct;
import com.xdx.service.ProductService;
@Controller
public class DemoController {
@Resource(name = "mailSender")
private JavaMailSender mailSender;
@Resource(name = "velocityEngine")
private VelocityEngine velocityEngine;
@Resource(name = "productService")
private ProductService productService; @ResponseBody
@RequestMapping(value = "simpleMailDemo", produces = "text/html; charset=utf-8")
public String simpleMailDemo() {
SimpleMailMessage mail = new SimpleMailMessage();
JavaMailSenderImpl mailSenderImpl = (JavaMailSenderImpl) mailSender;
// 发送方
mail.setFrom(mailSenderImpl.getUsername());
// 接收方
mail.setTo("2717814812@qq.com");
// 标题
mail.setSubject("spring mvc简单邮件发送");
// 设置邮件正文
mail.setText("spring mvc简单邮件发送,收到此邮件表明邮件模块配置成功");
mailSender.send(mail);
return "成功";
} @ResponseBody
@RequestMapping(value = "velocityMailDemo", produces = "text/html; charset=utf-8")
public String velocityMailDemo() throws UnsupportedEncodingException,
MessagingException {
JavaMailSenderImpl mailSenderImpl = (JavaMailSenderImpl) mailSender;
MimeMessage mimeMessage = mailSenderImpl.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "utf-8");
helper.setFrom(mailSenderImpl.getUsername(), "逸品周刊");
helper.setTo("2717814812@qq.com");
// 主题
helper.setSubject("velocity模板邮件发送");
String template = "test.vm";
List<TProduct> productList = productService.getHotProductList();//获取商品列表
Map<String, Object> model = new HashMap<String, Object>();
model.put("productList", productList);
String result = null;
try {
result = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, template, "UTF-8", model);
} catch (Exception e) {
}
helper.setText(result, true);
try {
mailSenderImpl.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
return "成功";
}
}

6.测试结果,图片是因为没有上传,所以没有显示出来。

使用javaMail和velocity来发送模板邮件

7.最后看一下,整个项目的目录。

使用javaMail和velocity来发送模板邮件