spring mvc 发送html格式velocity邮件模板(包括定时发送与按钮触发发送)

1.Maven Dependency(POM.xml)





  4.0.0
  war

  
  oschina
  oschina.simple
  1.0
  oschina.simple Maven Webapp
  http://maven.oschina.net/content/groups/public/

  
    
      
        org.mortbay.jetty
        maven-jetty-plugin
        6.1.7
        
          
            
              8888
              30000
            
          
          ${project.build.directory}/${pom.artifactId}-${pom.version}
          /
        
      
    
  

  
    
    
	
      javax.mail
      mail
      1.5.0-b01
    
    
		
		
			org.springframework
			spring-webmvc
			4.1.5.RELEASE
		
		
			org.springframework
			spring-web
			4.1.5.RELEASE
		
		
			org.springframework
			spring-context
			
				
				
					commons-logging
					commons-logging
				
			
			4.1.5.RELEASE
		
		
			org.springframework
			spring-context-support
			4.1.5.RELEASE
		
		
			org.springframework
			spring-beans
			4.1.5.RELEASE
		
		
			org.springframework
			spring-jdbc
			4.1.5.RELEASE
		
		
            org.apache.velocity
            velocity-tools
            2.0
        
        
          org.quartz-scheduler
          quartz
          2.2.1
        
  



2.Spring-MVC配置文件

包括web.xml,spring-servlet.xml,applicationContext.xml,spring-quartz.xml等配置文件以及mail.properties资源文件的配置。

web.xml配置文件:





  
    org.springframework.web.context.ContextLoaderListener
  

  
    org.springframework.web.context.request.RequestContextListener
  
  
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
      
         encoding
         UTF-8
      
      
        forceEncoding
        true
      
  
  
    encodingFilter
    /*
  
  
  
  
    contextConfigLocation
    /WEB-INF/config/applicationContext.xml
  

  
    log4jConfigLocation
    /WEB-INF/config/log4j.properties
  
  
    spring
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      
      /WEB-INF/config/spring-servlet.xml
      /WEB-INF/config/spring-quartz.xml
      
    
    1
  
  
    spring
    *.do
  

此处,我仍然使用spring3的配置方法。配置文件,被我放在web-app/WEB-INF/config下。


spring-servlet.xml配置文件:

  
      
       
       
     
      
       
     
     
       
         
     
     
      
      
     
     
     
      
 


applicationContext.xml配置文件:

   
     
  
  
  
    
      
        /WEB-INF/config/mail.properties
      
    
  
  
   
  
    
  

  
    
      
        ${Settings.mailtplt.from} 
        true
        UTF-8
        smtp
      
    
    
    
    
    
    
  
  
    
    
    
  
  
    
       
  
     
      
      
      
    
     
   
    
   
   
     
     
     
  


mail.properties资源文件:

Settings.mailserver.host=smtp.qq.com            此处使用qq邮箱smtp服务,当然也可以选择其他smtp服务

Settings.mailserver.username=######qq.com   此处注意加上@qq.com

Settings.mailserver.password=######         此处为qq邮箱开通smtp服务后的第二个密码

Settings.mailtplt.from=######@qq.com        注意要与Settings.mailserver.username内容保存一致,即同一个邮箱地址

Settings.mailserver.port=25                     大部分邮箱端口号都为25

mail.smtp.auth=true
mail.default.from=######@qq.com

spring-quartz.xml配置如下:



  

    
      
       
      
    
  
  
  
  
    
    
    
      
      0 47 10 * * ?
    
   
  
  
    
      
        
        
      
    
   


3.定时发送邮件代码:

com.cnood.schedule.action.SendMail类

package com.cnood.schedule.action;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.cnood.email.service.MailSenderService;

public class SendMail {
	
	@Autowired
	private MailSenderService mailSender;
	
	public void sendTimingMail(){
			int i;
			mailSender.setTo("[email protected]"); 
			mailSender.setSubject("文本测试邮件");  
			mailSender.setTemplateName("welcome.vm");//设置的邮件模板  
			Map model=new HashMap();  
			model.put("userName", "xxx"); //此处连续发送诗词次邮件模板
			for(i=0;i<10;i++){
				mailSender.sendWithTemplate(model);  
				System.out.println("邮件发送成功!");  
			}
		}
	

}
com.cnood.email.service.MailSenderService.java,这是一个发送邮件的工具类,代码如下:

package com.cnood.email.service;

import java.io.File;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class MailSenderService{
	
	private VelocityEngine velocityEngine;//spring配置中定义
	
	//private FreeMarkerConfigurer freeMarkerConfigurer;
	
	private JavaMailSender mailSender;//spring配置中定义

	private SimpleMailMessage simpleMailMessage;//spring配置中定义
	
    private String from;  
    private String to;  
    private String subject;  
    private String content;  
    private String templateName;
    // 是否需要身份验证     
    private boolean validate = false; 
	
	/*
	public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer){
		this.freeMarkerConfigurer = freeMarkerConfigurer;
	}
	*/ 
	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine){
		this.velocityEngine = velocityEngine;
	}
	
	public JavaMailSender getMailSender() {
		return mailSender;
	}
	
	public void setMailSender(JavaMailSender mailSender){
		this.mailSender = mailSender;
	}
	
	public SimpleMailMessage getSimpleMailMessage() {
		return simpleMailMessage;
	}

	public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
		this.simpleMailMessage = simpleMailMessage;
	}
	
    public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public String getSubject() {
		return subject;
	}

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

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getTemplateName() {
		return templateName;
	}

	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}
    
    /** 
     * 发送模板邮件 
     * 
     */  
    public void sendWithTemplate(Map model){  
        mailSender = this.getMailSender();  
        simpleMailMessage.setTo(this.getTo()); //接收人    
        simpleMailMessage.setFrom(simpleMailMessage.getFrom()); //发送人,从配置文件中取得  
        simpleMailMessage.setSubject(this.getSubject());  
        String result = null;  
        try {  
            result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8",model);  
        } catch (Exception e) {}  
        simpleMailMessage.setText(result);  
        mailSender.send(simpleMailMessage);  
    }  
    
    /** 
     * 发送普通Html模板邮件 
     * @throws MessagingException 
     * 
     */  
    public void sendHtml(Map model) throws MessagingException{  
        mailSender = this.getMailSender();  
        MimeMessage mimeMessage = mailSender.createMimeMessage();  
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true); 
        String result = null; 
        try {  
            result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8",model);  
        } catch (Exception e) {} 
        try {  
            messageHelper.setTo(this.getTo());  
            messageHelper.setFrom(simpleMailMessage.getFrom());  
            messageHelper.setSubject(this.getSubject());  
            messageHelper.setText(result,true);   
        } catch (MessagingException e) {   
            e.printStackTrace();  
        }  
        mailSender.send(mimeMessage); 
    }  
    

model之中,是传递的velocity模板中的注入的参数

第一个方法,只能发送纯文本模板,第二个方法则是可以发送html模板


4.邮件模板

welcome.vm

  
  
您好 $!{userName}, 欢迎您加入! 
此处模板的路径:webapp/WEB-INF/velocity/email/welcome.vm
在applicationContext.xml配置文件中,id为velocityEngine的bean中设置了路径

applicationContext.xml中velocityEngine还有另外一种写法,不过vm模板必须保存在WEB-INF/classes目录下才能读取

这种写法:

  
      
          
            file  
            .  
              
                org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader  
              
            UTF-8  
            UTF-8  
          
      
  


5.按钮触发邮件发送任务

mail.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>



My JSP 'user_add.jsp' starting page




邮件发送

此处只是做两个简单的按钮,注意jsp放在web-app目录下


action:com.cnood.email.action.SendTestEmail,代码如下:

package com.cnood.email.action;

import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cnood.email.service.MailSenderService;

@Controller
@RequestMapping("/email")
public class SendTestEmail {
	
	@Autowired
	private MailSenderService mailSender;
	
	@RequestMapping("/sendTextEmail.do")
	public void sendTestEmail(){
        mailSender.setTo("[email protected]"); 
	mailSender.setSubject("文本测试邮件");  
	mailSender.setTemplateName("welcome.vm");//设置的邮件模板  
	Map model=new HashMap();  
	model.put("userName", "xxx");  
	mailSender.sendWithTemplate(model);  
	System.out.println("邮件发送成功!");  
	}
	
	@RequestMapping("/sendHtmlEmail.do")
	public void sendHtmlEmail() throws MessagingException{
	mailSender.setTo("[email protected]"); 
	mailSender.setSubject("文本测试邮件");  
	mailSender.setTemplateName("welcome.vm");//设置的邮件模板  
	Map model=new HashMap();  
	model.put("userName", "xxx");  
	mailSender.sendHtml(model);
	System.out.println("邮件发送成功!"); 	
}}

 
  
好了,写下这么多,希望对读者能够产生一些帮助!














你可能感兴趣的:(spring mvc 发送html格式velocity邮件模板(包括定时发送与按钮触发发送))