1.在eclipse中新建一个Java Project, 命名为spring-velocity-mail
2.在项目下新建一个lib目录,导入需要的jar包
依赖包如下:
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.2.jar
mail.jar
spring-beans-3.2.2.jar
spring-context-3.2.2.jar
spring-context-support-3.2.2.jar
spring-core-3.2.2.jar
spring-expression-3.2.2.jar
velocity-1.5.jar
注:因为我用的JDK是1.7所以不用引入JAF的jar包
3.新建发送邮件抽象类SendMailBase.java, 内容如下:
packagecn.com.csii.mail;
importjava.util.Date;
importjava.util.Map;
importjavax.mail.internet.MimeMessage;
importorg.springframework.mail.javamail.JavaMailSenderImpl;
importorg.springframework.mail.javamail.MimeMessageHelper;
/**
* 邮件发送抽象类,该类的主要功能是封装发送邮件的一系列属性,和发送邮件的固定内容,还有一个抽象的方法生成邮件正文的方法,需要子类去覆盖
* @author liujianguo
*
*/
publicabstractclassSendMailBase {
/**
* 发送邮件主机
*/
privateString host = "localhost";
/**
* 连接到邮件发送服务器端口
*/
privateintport =25;
/**
* 邮件发送协议
*/
privateString protocol = "smtp";
/**
* 账户
*/
privateString username = "aaa";
/**
* 密码
*/
privateString password = "123";
/**
* 发件人邮箱地址
*/
privateString addresser = "[email protected]";
/**
* 收件人邮箱地址
*/
privateString recipient;
/**
* 邮件主题
*/
privateString subject;
/**
* 邮件模板位置
*/
privateString templateLocation;
publicString getHost() {
returnhost;
}
publicvoidsetHost(String host) {
this.host = host;
}
publicintgetPort() {
returnport;
}
publicvoidsetPort(intport) {
this.port = port;
}
publicString getProtocol() {
returnprotocol;
}
publicvoidsetProtocol(String protocol) {
this.protocol = protocol;
}
publicString getUsername() {
returnusername;
}
publicvoidsetUsername(String username) {
this.username = username;
}
publicString getPassword() {
returnpassword;
}
publicvoidsetPassword(String password) {
this.password = password;
}
publicString getAddresser() {
returnaddresser;
}
publicvoidsetAddresser(String addresser) {
this.addresser = addresser;
}
publicString getRecipient() {
returnrecipient;
}
publicvoidsetRecipient(String recipient) {
this.recipient = recipient;
}
publicString getSubject() {
returnsubject;
}
publicvoidsetSubject(String subject) {
this.subject = subject;
}
publicString getTemplateLocation() {
returntemplateLocation;
}
publicvoidsetTemplateLocation(String templateLocation) {
this.templateLocation = templateLocation;
}
/**
* 发送邮件, 在这方法内部会创建一封邮件,然后根据Velocity模板和传入Map模型,合并出邮件内容,并发送出去
* @parammodel
* @throwsException
*/
@SuppressWarnings("rawtypes")
publicvoidsendMail(Map model) throws Exception{
JavaMailSenderImpl sender = newJavaMailSenderImpl();
sender.setHost(host);
sender.setUsername(username);
sender.setPassword(password);
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = newMimeMessageHelper(message, "UTF-8"); //为了解决中文乱码问题
//设置发件人
helper.setFrom(addresser);
//设置收件人
String recipientInModel =(String) model.get("recipient");
if(recipientInModel != null&& !"".equals(recipientInModel.trim())){
helper.setTo(recipientInModel);
}
else{
helper.setTo(recipient);
}
//设置邮件主题
helper.setSubject(subject);
//设置邮件发送时间
helper.setSentDate(newDate());
//设置邮件正文
String text =createMailText(model);
helper.setText(text, true); //如果模板里是html代码, 那么这个一定要设置为true
//发送邮件
sender.send(message);
}
/**
* 生成邮件正文
* @parammodel
* @return
*/
protectedabstractString createMailText(Map model);
}
4.创建根据Velocity模板发送邮件的子类,继承SendMailBase.java
packagecn.com.csii.mail;
importjava.util.Map;
importorg.apache.velocity.app.VelocityEngine;
importorg.springframework.ui.velocity.VelocityEngineUtils;
/**
* 使用Spring结合Velocity模板发送邮件的工具类
*/
publicclassSendMailByVelocityTemplate extends SendMailBase {
/**
* 依赖的Velocity类
*/
privateVelocityEngine velocityEngine;
publicVelocityEngine getVelocityEngine() {
returnvelocityEngine;
}
publicvoidsetVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
@Override
protectedString createMailText(Map model) {
String templateLocation =getTemplateLocation();
String text =VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, "UTF-8", model);
returntext;
}
}
5.新建一个邮件模板(regist-template.vm)放在src目录下,内容如下:
<html>
<body>
<h3>Hi, ${username}, welcome to the Email</h3>
<div>
now, you are registsuccessfully!
</div>
</body>
</html>
6.配置beans.xml文件
第一个配置,如下:
<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>
第二个配置,如下:
<bean id="sendMailByVelocityTemplate"class="cn.com.csii.mail.SendMailByVelocityTemplate">
<property name="addresser" value="[email protected]"/>
<property name="recipient" value="[email protected]"/>
<property name="templateLocation" value="regist-template.vm" />
<property name="host" value="localhost"/>
<property name="username" value="aaa"/>
<property name="password" value="123"/>
<property name="subject" value="使用Spring-Velocity发送邮件" />
<property name="velocityEngine" ref="velocityEngine" />
</bean>
注意:这里我是在自己电脑上装了一个邮箱服务器软件,所以host属性是localhost,如果你自己练习,完全可以使用实际的邮箱地址,比如新浪,QQ,162,sohu等
7.创建客户端测试类
packagecn.com.csii.mail.client;
importjava.util.HashMap;
importjava.util.Map;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importcn.com.csii.mail.SendMailBase;
publicclassMailSendClient {
publicstaticvoidmain(String[] args) throws Exception {
ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
SendMailBase sendMailImpl =
(SendMailBase) context.getBean("sendMailByVelocityTemplate");
Map model = newHashMap();
model.put("username", "李四");
sendMailImpl.sendMail(model);
}
}
8.运行这个客户端程序, 查看是否能收到邮件