Spring通过对Javamail的封装来简化发送email的步骤,提供易于使用的接口,发送时通过发送html类邮件或者结合velocity更能够提供样式丰富的邮件。需要引入spring的jar包(特别是spring-context-support-RELEASE.jar)及mail-1.4.5.jar。
首先定义自己的邮件发送工具类,封装用到的velocity引擎,邮件的主题、内容、模板等信息,然后提供邮件发送方法,使用spring提供的邮件接口实现类org.springframework.mail.javamail.JavaMailSenderImpl来发送邮件。
package com.xx.tools;import java.util.Map;import javax.mail.internet.MimeMessage;import org.apache.velocity.app.VelocityEngine;import org.springframework.mail.javamail.JavaMailSenderImpl;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.ui.velocity.VelocityEngineUtils;public class SpringMailSender { private JavaMailSenderImpl mailSender; private VelocityEngine velocityEngine; private String subject; private String content; private String templateName; public static void main(String[] args) { } public void sendGongDanMail() { } public void sendMail(String[] toArray, String[] ccArray, Mapmodel) { // 建立邮件消息 MimeMessage msg = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(msg, true); helper.setTo(toArray); // 接收人 helper.setCc(ccArray); helper.setFrom("your@163.com"); // 发送人 helper.setSubject(this.getSubject()); String result = null; //通过velocity组织内容,model存放模板中用到的变量 result = VelocityEngineUtils.mergeTemplateIntoString( this.getVelocityEngine(), this.getTemplateName(), "GBK", model); //第二个参数为true,表示发送 "text/html" 类的HTML mail,默认发送 类型为"text/plain"的邮件 helper.setText(result, true); // 发送邮件 mailSender.send(msg); } catch (Exception e) { System.out.println(e); } System.out.println(" 邮件发送成功.. "); } public VelocityEngine getVelocityEngine() { return velocityEngine; } public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } 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 JavaMailSenderImpl getMailSender() { return mailSender; } public void setMailSender(JavaMailSenderImpl mailSender) { this.mailSender = mailSender; }}
使用velocity的话,如果要在模板中调用java方法,需要新建一个对象,然后将引用放到model中,如下:
StringUtil stringutil = new StringUtil();
Map<String, Object> model=new HashMap<String, Object>(); model.put("stringutil", stringutil);这样就能在vm模板中调用java方法,获得需要的结果了。
在applicationContext.xml中配置上面我们定义的工具类SpringMailSender,以及用到的velocityEngine,JavaMailSenderImpl(构造时提供邮件服务器信息已经发送邮件用到的用户名、密码等信息)。
true 25000 class org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader