Spring+javamail+velocity发送邮件

1 篇文章 0 订阅
1 篇文章 0 订阅

最精做到一个项目需要用到邮箱验证,所研究了一下

 

首先需要jar包:

org.springframework.context.support-3.1.2.RELEASE.jar (封装了javamail的相关api)

mail.jar;   velocity-1.4.jar  velocity-tools-view-1.2.jar    activation.jar    commons-collections-3.2.jar   dsn.jar  imap.jar   pop3.jar  smtp.jar(为了防止出现位置错误,所以就全导入了)

 

首先建议一个  mail.properties  配置相关的信息

 

#必要的信息,服务器,用户名,密码,端口
host=smtp.163.com
username=yourEmail
password=yourPassword
port=25
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.smtp.starttls.enable=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.port=25
mail.smtp.socketFactory.fallback=false

#默认发送者
mail.default.from=CoderZone<coderzone@163.com>
#默认标题
mail.default.subject=默认标题
mail.default.contentType=text/html; charset=GBK

#不同类型邮件模板
mail.findPassword.subject=默认的模板标题
mail.findPassword.template=模板VM文件路径

 

然后配置Spring配置文件,同Spring的注入,大大的方便了我们编程

 

新建一个mailbean.xml

 

<?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-2.5.xsd
         
           ">

	<!-- 邮箱配置文件读取 -->
	<bean name="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:mail.properties</value>
			</list>
		</property>
	</bean>

	<!-- 邮件的发送器,非常的重要 ,传入配置文件的信息-->
	<bean name="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host">
			<value>${host}</value>
		</property>
		<property name="username">
			<value>${username}</value>
		</property>
		<property name="password">
			<value>${password}</value>
		</property>
		<property name="port">
			<value>${port}</value>
		</property>

		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
				<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
				<prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
				<prop key="mail.smtp.socketFactory.port">${mail.smtp.socketFactory.port}</prop>
				<prop key="mail.smtp.socketFactory.fallback">${mail.smtp.socketFactory.fallback}</prop>
			</props>

		</property>
	</bean>

	<!-- 邮件发送工具,也是一个基础的模板类,其他类型的模板都是"继承"这个的 -->
	<bean name="baseMailTemplate" class="com.workroom518.coderzone.util.VelocityMailUtil"
		abstract="true">
		<property name="velocityEngine" ref="velocityEngine" />
		<property name="mailHeaders">
			<props>
				<prop key="Content-Type">
					${mail.default.contentType}
				</prop>
			</props>
		</property>
		<property name="from">
			<value>${mail.default.from}</value>
		</property>
	</bean>

	<!-- 读取velocity模板的工厂类,也就是的不同的模板的 -->
	<bean id="velocityEngine"
		class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
		<property name="velocityProperties">
			<props>
				<!-- 设置从classPath下读取模板文件 vm文件 -->
				<prop key="resource.loader">class</prop>
				<prop key="class.resource.loader.class">
					org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
				</prop>
				<prop key="velocimacro.library"></prop>
			</props>
		</property>
	</bean>

</beans>


基本配置完成了,下面就是配置相应的模板了,新建一个 mailmodel.xml,这里我有两个模板,一个是激活帐号的,一个是找回密码的

 

 

别忘了把这两个xml文件包含到主配置文件里去哦

 

<?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="activationMailTemplate" parent="baseMailTemplate">
		<property name="subject">
			<value>${mail.activation.subject}</value>
		</property>
		<property name="templateName">
			<value>${mail.activation.template}</value>
		</property>
	</bean>
	
	
	<bean id="findPasswordMailTemplate" parent="baseMailTemplate">
		<property name="subject">
			<value>${mail.findPassword.subject}</value>
		</property>
		<property name="templateName">
			<value>${mail.findPassword.template}</value>
		</property>
	</bean>
	
	
</beans>
	

接下来就是主要的操作类了 VelocityMailUtil.java

 

 

package com.workroom518.coderzone.util;


import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;


/**
 * 类描述:邮件发送模板
 * @author zzy
 * @date: 日期:2012-9-29 时间:上午10:58:21
 * @version 1.0
 */
public class VelocityMailUtil{

	
	private Properties mailHeaders = new Properties();
	
	/**
	 * 邮件发送者,包括发送者姓名和地址,用于设置在邮件的from栏目中
	 */
	private String from;

	/**
	 * 邮件主题
	 */
	private String subject;

	/**
	 * 邮件内容模板地址/名称
	 */
	private String templateName;

	/**
	 * velocity引擎
	 */
	private VelocityEngine velocityEngine;

	/**
	 * JavMail发送器,通过Spring诸注入
	 */
	@Autowired
	private JavaMailSender mailSender;


	/**
	 * 使用提供的数据,套入velocity模板,生成最后文本信息。
	 * 
	 * 大部分情况下,这个信息应该就是邮件的内容。
	 */
	public String renderText(Map model) throws VelocityException {
		//防止乱码,需设置为GBK
		return VelocityEngineUtils.mergeTemplateIntoString(getVelocityEngine(),
				getTemplateName(),"GBK", model);
	}


	public Properties getMailHeaders() {
		return mailHeaders;
	}


	/**
	 * 设置非空mime hader,一般可以利用此设置contentType等
	 * @param mailHeaders
	 */
	public void setMailHeaders(Properties mailHeaders) {
		this.mailHeaders = mailHeaders;
	}
	
	
	public String getFrom() {
		return this.from;
	}
	
	public Address getFromAddress() throws AddressException {
		return new InternetAddress(this.from);
	}

	/**
	 * 设置邮件发送者,包括发送者姓名和地址,用于设置在邮件的from栏目中
	 * 
	 * @param from
	 */
	public void setFrom(String from) {
		this.from = from;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getTemplateName() {
		return templateName;
	}

	/**
	 * 设置邮件内容模板地址/名称
	 * 
	 * @param templateName
	 */
	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}

	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	
	/**
	 * 获取下层配置的mail发送器,发送邮件, 该mail发送器必须是JavaMailSender,否则抛出CaseException。
	 * 
	 * @return
	 */
	public JavaMailSender getJavaMailSender() {
		return (JavaMailSender)mailSender;
	}

	/**
	 * 设置mail发送器
	 * 
	 * @param mailEngine
	 */
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	
	/**
	 * 
	 * 发送Mime邮件简易方法。
	 * 
	 * 以Mime的方式发送邮件,这主要是为能够支持发送html或类似功能(非简单文本)的邮件
	 * 
	 * @param nameOfTo 邮件接收收人姓名 或 昵称
	 * @param emailOfTo 邮件接收人邮件地址
	 * @param model 邮件velocity模板中变量的值
	 * @throws MailException
	 */
	public void sendMime(String nameOfTo, String emailOfTo, Map<String, Object> model) throws MailException {
		sendMime(nameOfTo + "<" + emailOfTo + ">", model);
	}

	
	/**
	 *  发送Mime邮件简易方法。
	 * 
	 * 以Mime的方式发送邮件,这主要是为能够支持发送html或类似功能(非简单文本)的邮件
	 * 
	 * @param to 邮件接收人邮件地址以及可能的收件人姓名或昵称
	 * @param model 邮件velocity模板中变量的值
	 */
	public void sendMime(String to, Map<String, Object> model) throws MailException {
		sendMime(mergeSimpleMessage(to, model));
	}
	

	/**
	 * 发送Mime邮件简易方法。
	 * 
	 * 以Mime的方式发送SimpleMailMessage,这主要是为能够支持发送html或类似功能(非简单文本)的邮件
	 * 
	 * @param simpleMessage
	 * @throws MailException
	 */
	public void sendMime(SimpleMailMessage simpleMessage) throws MailException {
		mailSender.send(toMimeMessage(simpleMessage));
	}
	

	
	/**
	 * 产生简单信息
	 * @param to
	 * @param model
	 * @return
	 */
	public SimpleMailMessage mergeSimpleMessage(String to, Map<String, Object> model) {
		//render text of mail from velocity template with the data
		String text = null;
		try {
			text = renderText(model);
		} catch (VelocityException e) {
			e.printStackTrace();
		}
		
		System.out.println(text);
		
		//mail message setting
		SimpleMailMessage message = new SimpleMailMessage();
		message.setSubject(getSubject());
		message.setFrom(getFrom());
		message.setTo(to);
		message.setText(text);
		return message;
	}
	
	/**
	 * 产生html文本信息
	 * @param simpleMailMessage
	 * @return
	 */
	public MimeMessagePreparator toMimeMessage(final SimpleMailMessage simpleMailMessage) {
		 MimeMessagePreparator preparator = new MimeMessagePreparator(){

			public void prepare(MimeMessage mimeMessage) throws Exception {
				// TODO Auto-generated method stub
				 MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"GBK");
				 message.setTo(simpleMailMessage.getTo());
				 message.setSubject(simpleMailMessage.getSubject());
				 message.setText(simpleMailMessage.getText(),true);
				 message.setFrom(simpleMailMessage.getFrom());
			}
			 
		 };
		
		return preparator;	
	}
}


下面就是模板文件了 举一个例子 account_activity.vm

 

此处的 $!{user}  为占位符,具体替换为你在 VelocityMailUtil中传入的map文件,根据键值对进行替换。

要注意的这个vm文件放置的位置,前面我们设置了是从classPath下读取(因为不同的运行环境路径不同,所以还是不要设置绝对路径了),把这里路径写在mail.properties就可以了

 

<html>
<body>
<h3>您好 $!{username}, 欢迎您加入CoderZone!</h3>
 
<div>
    	您的email地址是<a href="$!{url}">$!{url}</a>.
  		本条信息是系统自动发送,请勿回复!
</div>
</body>
 
</html>
到这里就一切OK了,怎么调用就不说了把,直接调用VelocityMailUtil的sendMime方法就可以了,自己去试试把

 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值