介绍 如何使用Spring mail api 来发送email,用velocityEngine 解析邮件模板,这里会用一个完整的Spring mail 发送邮件的例子来演示它发送email的过程。您会欣赏到 Spring mail 的丰富功能,以及它是如何简化开发任务的.
Spring Mail API
Spring Mail API都在org.springframework.mail及其子包org.springframework.mail.javamail中封装。
JavaMailSenderImpl: 邮件发送器,主要提供了邮件发送接口、透明创建Java Mail的MimeMessage、及邮件发送的配置(如:host/port/username/password...)。
MimeMailMessage、MimeMessageHelper:对MimeMessage进行了封装。Spring还提供了一个回调接口MimeMessagePreparator, 用于准备JavaMail的MIME信件.
上代码,MailUtil类负责发送,MailBean类封装邮件信息。只有这两个类了简单吧
MailUtil.java
- package com.dr.sm.mail;
- import java.io.IOException;
- import java.io.StringWriter;
- import java.io.UnsupportedEncodingException;
- import javax.mail.MessagingException;
- import javax.mail.internet.MimeMessage;
- import org.apache.log4j.Logger;
- import org.apache.velocity.VelocityContext;
- import org.apache.velocity.app.VelocityEngine;
- import org.apache.velocity.exception.VelocityException;
- import org.springframework.mail.javamail.JavaMailSender;
- import org.springframework.mail.javamail.MimeMessageHelper;
- /**
- * spring发送mail工具
- * @author: haleywang,@created on: 2012-9-20
- */
- public class MailUtil {
- Logger log = Logger.getLogger(MailUtil.class);
- private JavaMailSender javaMailSender;
- private VelocityEngine velocityEngine; //模板解析
- /**
- * @param mailBean
- * @return
- * @throws MessagingException
- */
- public boolean send(MailBean mailBean) throws MessagingException {
- MimeMessage msg = createMimeMessage(mailBean);
- if(msg == null){
- return false;
- }
- this.sendMail(msg, mailBean);
- return true;
- }
- private void sendMail(MimeMessage msg, MailBean mailBean){
- javaMailSender.send(msg);
- log.info("$$$ Send mail Subject:" + mailBean.getSubject()
- + ", TO:" + arrayToStr(mailBean.getToEmails()) );
- }
- /*
- * 记日记用的
- */
- private String arrayToStr(String[] array){
- if(array == null || array.length == 0){
- return null;
- }
- StringBuffer sb = new StringBuffer();
- for(String str : array){
- sb.append(str+" , ") ;
- }
- return sb.toString();
- }
- /*
- * 根据 mailBean 创建 MimeMessage
- */
- private MimeMessage createMimeMessage(MailBean mailBean) throws MessagingException {
- if (!checkMailBean(mailBean)) {
- return null;
- }
- String text = getMessage(mailBean);
- if(text == null){
- log.warn("@@@ warn mail text is null (Thread name="
- + Thread.currentThread().getName() + ") @@@ " + mailBean.getSubject());
- return null;
- }
- MimeMessage msg = javaMailSender.createMimeMessage();
- MimeMessageHelper messageHelper = new MimeMessageHelper(msg, true, "UTF-8");
- //messageHelper.setFrom(mailBean.getFrom());
- try {
- messageHelper.setFrom(mailBean.getFrom(), mailBean.getFromName());
- } catch (UnsupportedEncodingException e) {
- log.error(e);
- }
- messageHelper.setSubject(mailBean.getSubject());
- messageHelper.setTo(mailBean.getToEmails());
- messageHelper.setText(text, true); // html: true
- return msg;
- }
- /*
- * 模板解析
- * @param mailBean
- * @return
- */
- private String getMessage(MailBean mailBean) {
- StringWriter writer = null;
- try {
- writer = new StringWriter();
- VelocityContext context = new VelocityContext(mailBean.getData());
- velocityEngine.evaluate(context, writer, "", mailBean.getTemplate());
- return writer.toString();
- } catch (VelocityException e) {
- log.error(" VelocityException : " + mailBean.getSubject() + "\n" + e);
- } catch (IOException e) {
- log.error(" IOException : " + mailBean.getSubject() + "\n" + e);
- } finally {
- if (writer != null) {
- try {
- writer.close();
- } catch (IOException e) {
- log.error("###StringWriter close error ... ");
- }
- }
- }
- return null;
- }
- /*
- * check 邮件
- */
- private boolean checkMailBean(MailBean mailBean){
- if (mailBean == null) {
- log.warn("@@@ warn mailBean is null (Thread name="
- + Thread.currentThread().getName() + ") ");
- return false;
- }
- if (mailBean.getSubject() == null) {
- log.warn("@@@ warn mailBean.getSubject() is null (Thread name="
- + Thread.currentThread().getName() + ") ");
- return false;
- }
- if (mailBean.getToEmails() == null) {
- log.warn("@@@ warn mailBean.getToEmails() is null (Thread name="
- + Thread.currentThread().getName() + ") ");
- return false;
- }
- if (mailBean.getTemplate() == null) {
- log.warn("@@@ warn mailBean.getTemplate() is null (Thread name="
- + Thread.currentThread().getName() + ") ");
- return false;
- }
- return true;
- }
- /*===================== setter & getter =======================*/
- public void setJavaMailSender(JavaMailSender javaMailSender) {
- this.javaMailSender = javaMailSender;
- }
- public void setVelocityEngine(VelocityEngine velocityEngine) {
- this.velocityEngine = velocityEngine;
- }
- }
MailBean
- package com.dr.sm.mail;
- import java.io.Serializable;
- import java.util.Map;
- public class MailBean implements Serializable {
- private String from;
- private String fromName;
- private String[] toEmails;
- private String subject;
- private Map data ; //邮件数据
- private String template; //邮件模板
- //省略setter&getter方法
- }
接着就是配置文件了,applicationContext.xml,applicationContext-mail.xml
applicationContext.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"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
- ">
- <!-- ================2.自动扫描的包名===================== -->
- <context:component-scan base-package="com.dr.sm" />
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath:mail.properties</value>
- </list>
- </property>
- </bean>
- <import resource="classpath:applicationContext-mail.xml"/>
- </beans>
applicationContext-mail.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"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
- ">
- <!-- 邮件发送器 163 -->
- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
- <property name="host" value="${mail.host}" />
- <property name="username" value="${mail.username}" />
- <property name="password" value="${mail.password}" />
- <property name="defaultEncoding" value="UTF-8"></property>
- <property name="javaMailProperties">
- <props>
- <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
- <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
- </props>
- </property>
- </bean>
- <!-- 邮件发送器 gmail
- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
- <property name="host" value="${mail.host}" />
- <property name="username" value="${mail.username}" />
- <property name="password" value="${mail.password}" />
- <property name="defaultEncoding" value="UTF-8"></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.port">465</prop>
- <prop key="mail.smtp.socketFactory.port">465</prop>
- <prop key="mail.smtp.socketFactory.fallback">false</prop>
- <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
- </props>
- </property>
- </bean>
- -->
- <bean id="velocityEngine"
- class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
- </bean>
- <bean id="mailUtil" class="com.dr.sm.mail.MailUtil">
- <property name="javaMailSender" ref="mailSender"></property>
- <property name="velocityEngine" ref="velocityEngine"></property>
- </bean>
- </beans>
mail.properties
- mail.from=wzqdemo@163.com
- mail.host=smtp.163.com
- mail.password=********
- mail.smtp.auth=true
- mail.smtp.timeout=25000
- mail.username=wzqdemo
- #mail.from=wzqdemo@163.com
- #mail.host=smtp.gmail.com
- #mail.password=********
- #mail.smtp.auth=true
- #mail.smtp.timeout=25000
- #mail.username=wzqdemo@gmail.com
jar包:
- activation.jar
- commons-collections-3.2.jar
- commons-lang-2.3.jar
- commons-logging-1.1.1.jar
- junit-4.10.jar
- log4j-1.2.15.jar
- mail.jar
- spring-asm-3.0.6.RELEASE.jar
- spring-beans-3.0.6.RELEASE.jar
- spring-context-3.0.6.RELEASE.jar
- spring-context-support-3.0.6.RELEASE.jar
- spring-context.jar
- spring-core-3.0.6.RELEASE.jar
- spring-expression-3.0.6.RELEASE.jar
- spring-jdbc-3.0.6.RELEASE.jar
- spring-test-3.0.6.RELEASE.jar
- spring-tx-3.0.6.RELEASE.jar
- spring-xml-1.5.10.jar
- velocity-1.6.4.jar
ok,终于可以开始测试咯!
- package com.dr.sm.mail;
- import java.util.HashMap;
- import java.util.Map;
- import javax.annotation.Resource;
- import javax.mail.MessagingException;
- import org.junit.Test;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
- @ContextConfiguration("classpath:applicationContext.xml")
- public class MailServiceTest extends AbstractJUnit4SpringContextTests {
- @Resource
- private MailUtil mailUtil;
- @Test
- public void testSendMail() {
- //创建邮件
- MailBean mailBean = new MailBean();
- mailBean.setFrom("wzqdemo@163.com");
- mailBean.setSubject("hello world");
- mailBean.setToEmails(new String[]{"wzqdemo@gmail.com"});
- mailBean.setTemplate("hello ${userName} !<a href='www.baidu.com' >baidu</a>");
- Map map = new HashMap();
- map.put("userName", "Haley Wang");
- mailBean.setData(map);
- //发送邮件
- try {
- mailUtil.send(mailBean);
- } catch (MessagingException e) {
- e.printStackTrace();
- }
- }