spring+velocity+javamail发送模板邮件

有时候当我们注册完的时候系统会提示有一封邮件发送到了你的邮箱,如何做呢?
就要用到spring+velocity+javamail这3个玩意,其实只用了spring,因为其他2个都被spring集成了。
先看代码
package com.worthtech.app.util;

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 JavaMailSender mailSender;//spring配置中定义
	private VelocityEngine velocityEngine;//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 JavaMailSender getMailSender() {
		return mailSender;
	}
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}
	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}
	/**
	 * 发送模板邮件
	 *
	 */
	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(this.getVelocityEngine(), this.getTemplateName(), "UTF-8",model);
		} catch (Exception e) {}
		simpleMailMessage.setText(result);
        mailSender.send(simpleMailMessage);
	}
	/**
	 * 发送普通文本邮件
	 *
	 */
	public void sendText(){
		mailSender = this.getMailSender();
		simpleMailMessage.setTo(this.getTo()); //接收人  
		simpleMailMessage.setFrom(simpleMailMessage.getFrom()); //发送人,从配置文件中取得
		simpleMailMessage.setSubject(this.getSubject());
		simpleMailMessage.setText(this.getContent());
	    mailSender.send(simpleMailMessage);
	}
	/**
	 * 发送普通Html邮件
	 *
	 */
	public void sendHtml(){
		mailSender = this.getMailSender();
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
		try {
			messageHelper.setTo(this.getTo());
			messageHelper.setFrom(simpleMailMessage.getFrom());
			messageHelper.setSubject(this.getSubject());
			messageHelper.setText(this.getContent(),true);      
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    mailSender.send(mimeMessage);
	}
	/**
	 * 发送普通带一张图片的Html邮件
	 *
	 */
	public void sendHtmlWithImage(String imagePath){
		mailSender = this.getMailSender();
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
			messageHelper.setTo(this.getTo());
			messageHelper.setFrom(simpleMailMessage.getFrom());
			messageHelper.setSubject(this.getSubject());
			messageHelper.setText(this.getContent(),true);
//			Content="<html><head></head><body><img src=\"cid:image\"/></body></html>";
			//图片必须这样子:<img src='cid:image'/>
			FileSystemResource img = new FileSystemResource(new File(imagePath));
			messageHelper.addInline("image",img);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    mailSender.send(mimeMessage);
	}
	/**
	 * 发送普通带附件的Html邮件
	 *
	 */
	public void sendHtmlWithAttachment(String filePath){
		mailSender = this.getMailSender();
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
			messageHelper.setTo(this.getTo());
			messageHelper.setFrom(simpleMailMessage.getFrom());
			messageHelper.setSubject(this.getSubject());
			messageHelper.setText(this.getContent(),true);
			FileSystemResource file = new FileSystemResource(new File(filePath));
//			System.out.println("file.getFilename==="+file.getFilename());
			messageHelper.addAttachment(file.getFilename(),file);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    mailSender.send(mimeMessage);
	}
	public String getFrom() {
		return from;
	}
	public void setFrom(String from) {
		this.from = from;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getTo() {
		return to;
	}
	public void setTo(String to) {
		this.to = to;
	}
	public String getTemplateName() {
		return templateName;
	}
	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public boolean isValidate() {
		return validate;
	}
	public void setValidate(boolean validate) {
		this.validate = validate;
	}
	public SimpleMailMessage getSimpleMailMessage() {
		return simpleMailMessage;
	}
	public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
		this.simpleMailMessage = simpleMailMessage;
	}
}


上面这个类实际上是个发送邮件的工具类,我们只要设置好参数后调用想要的sendXXX()就可以了。如下:
//注册完马上发送邮件
MailSenderService mailSender=this.getMailsenderService();
mailSender.setTo(form.getEmail());
mailSender.setSubject("来自worthtech的邮件");
mailSender.setTemplateName("mail.vm");//设置的邮件模板
Map model=new HashMap();
model.put("username", form.getUserName());
String url=request.getRequestURL().toString();
url=url.substring(0, url.lastIndexOf("/"));
model.put("url", url);
model.put("email", "[email protected]");
mailSender.sendWithTemplate(model);
System.out.println("邮件发送成功!");

下面的是spring配置
<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.starttls.enable">true</prop>
                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
                <prop key="mail.smtp.socketFactory.fallback">false</prop>
                -->
            </props>
        </property>
  </bean>
  <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage" singleton="false">
    <property name="from">
        <value>${mail.default.from}</value>
    </property>
  </bean>
  <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">   
            <props>   
                <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>
	<bean id="mailsenderService" class="com.worthtech.app.util.MailSenderService">  
	      <property name="mailSender" ref="mailSender" />
	      <property name="simpleMailMessage" ref="simpleMailMessage" />
	      <property name="velocityEngine" ref="velocityEngine" />
	</bean>


mail.vm内容如下:
亲爱的${username}

欢迎加入worthtech! 

当您收到这封信的时候,您已经可以正常登录了。
请点击链接登录首页:${url}
如果您的email程序不支持链接点击,请将上面的地址拷贝至您的浏览器(如IE)的地址栏进入。

如果您还想申请管理员权限,可以联系管理员${email}

我们对您产生的不便,深表歉意。

希望您在worthtech度过快乐的时光!
    
-----------------------
     
(这是一封自动产生的email,请勿回复。)


mail.properties如下:
mail.host=218.000.000.234
mail.port=25
[email protected]
mail.password=xxxxxxxx
mail.smtp.auth=true
mail.smtp.timeout=25000
[email protected]

你可能感兴趣的:(spring,.net,配置管理,IE,velocity)