码迷,mamicode.com
首页 > 编程语言 > 详细

Spring+Velocity模板发送邮件

时间:2015-08-06 22:39:48      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:java   mail   spring   velocity   

Spring+Velocity模板发送邮件

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

 

注:因为我用的JDK1.7所以不用引入JAFjar


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 = "aaa@jianguo6.com";

  

   /**

    * 收件人邮箱地址

    */

   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="aaa@jianguo6.com"/>

      <property name="recipient" value="bbb@jianguo6.com"/>

      <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如果你自己练习,完全可以使用实际的邮箱地址,比如新浪,QQ162sohu


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.运行这个客户端程序, 查看是否能收到邮件



Spring+Velocity模板发送邮件

标签:java   mail   spring   velocity   

原文地址:http://zhiyou.blog.51cto.com/10597348/1682387

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!