spring+velocity+javamail发送模板邮件

【转】spring+velocity+javamail发送模板邮件
有时候当我们注册完的时候系统会提示有一封邮件发送到了你的邮箱,如何做呢?
就要用到spring+velocity+javamail这3个玩意,其实只用了spring,因为其他2个都被spring集成了。
先看代码
  1 package  com.worthtech.app.util;
  2
  3 import  java.io.File;
  4 import  java.util.Map;
  5
  6 import  javax.mail.MessagingException;
  7 import  javax.mail.internet.MimeMessage;
  8
  9 import  org.apache.velocity.app.VelocityEngine;
 10 import  org.springframework.core.io.FileSystemResource;
 11 import  org.springframework.mail.SimpleMailMessage;
 12 import  org.springframework.mail.javamail.JavaMailSender;
 13 import  org.springframework.mail.javamail.MimeMessageHelper;
 14 import  org.springframework.ui.velocity.VelocityEngineUtils;
 15
 16 public   class  MailSenderService  {
 17    private JavaMailSender mailSender;//spring配置中定义
 18    private VelocityEngine velocityEngine;//spring配置中定义
 19    private SimpleMailMessage simpleMailMessage;//spring配置中定义
 20    private String from;
 21    private String to;
 22    private String subject;
 23    private String content;
 24    private String templateName;
 25    // 是否需要身份验证   
 26    private boolean validate = false
 27    
 28    
 29    public JavaMailSender getMailSender() {
 30        return mailSender;
 31    }

 32    public void setMailSender(JavaMailSender mailSender) {
 33        this.mailSender = mailSender;
 34    }

 35    public VelocityEngine getVelocityEngine() {
 36        return velocityEngine;
 37    }

 38    public void setVelocityEngine(VelocityEngine velocityEngine) {
 39        this.velocityEngine = velocityEngine;
 40    }

 41    /** *//**
 42     * 发送模板邮件
 43     *
 44     */

 45    public void sendWithTemplate(Map model){
 46        mailSender = this.getMailSender();
 47        simpleMailMessage.setTo(this.getTo()); //接收人  
 48        simpleMailMessage.setFrom(simpleMailMessage.getFrom()); //发送人,从配置文件中取得
 49        simpleMailMessage.setSubject(this.getSubject());
 50        String result = null;
 51        try {
 52            result = VelocityEngineUtils.mergeTemplateIntoString(this.getVelocityEngine(), this.getTemplateName(), "UTF-8",model);
 53        }
 catch (Exception e) {}
 54        simpleMailMessage.setText(result);
 55        mailSender.send(simpleMailMessage);
 56    }

 57    /** *//**
 58     * 发送普通文本邮件
 59     *
 60     */

 61    public void sendText(){
 62        mailSender = this.getMailSender();
 63        simpleMailMessage.setTo(this.getTo()); //接收人  
 64        simpleMailMessage.setFrom(simpleMailMessage.getFrom()); //发送人,从配置文件中取得
 65        simpleMailMessage.setSubject(this.getSubject());
 66        simpleMailMessage.setText(this.getContent());
 67        mailSender.send(simpleMailMessage);
 68    }

 69    /** *//**
 70     * 发送普通Html邮件
 71     *
 72     */

 73    public void sendHtml(){
 74        mailSender = this.getMailSender();
 75        MimeMessage mimeMessage = mailSender.createMimeMessage();
 76        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
 77        try {
 78            messageHelper.setTo(this.getTo());
 79            messageHelper.setFrom(simpleMailMessage.getFrom());
 80            messageHelper.setSubject(this.getSubject());
 81            messageHelper.setText(this.getContent(),true);      
 82        }
 catch (MessagingException e) {
 83            // TODO Auto-generated catch block
 84            e.printStackTrace();
 85        }

 86        mailSender.send(mimeMessage);
 87    }

 88    /** *//**
 89     * 发送普通带一张图片的Html邮件
 90     *
 91     */

 92    public void sendHtmlWithImage(String imagePath){
 93        mailSender = this.getMailSender();
 94        MimeMessage mimeMessage = mailSender.createMimeMessage();
 95        try {
 96            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
 97            messageHelper.setTo(this.getTo());
 98            messageHelper.setFrom(simpleMailMessage.getFrom());
 99            messageHelper.setSubject(this.getSubject());
100            messageHelper.setText(this.getContent(),true);
101//            Content="<html><head></head><body><img src=\"cid:image\"/></body></html>";
102            //图片必须这样子:<img src='cid:image'/>
103            FileSystemResource img = new FileSystemResource(new File(imagePath));
104            messageHelper.addInline("image",img);
105        }
 catch (MessagingException e) {
106            // TODO Auto-generated catch block
107            e.printStackTrace();
108        }

109        mailSender.send(mimeMessage);
110    }

111    /** *//**
112     * 发送普通带附件的Html邮件
113     *
114     */

115    public void sendHtmlWithAttachment(String filePath){
116        mailSender = this.getMailSender();
117        MimeMessage mimeMessage = mailSender.createMimeMessage();
118        try {
119            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
120            messageHelper.setTo(this.getTo());
121            messageHelper.setFrom(simpleMailMessage.getFrom());
122            messageHelper.setSubject(this.getSubject());
123            messageHelper.setText(this.getContent(),true);
124            FileSystemResource file = new FileSystemResource(new File(filePath));
125//            System.out.println("file.getFilename==="+file.getFilename());
126            messageHelper.addAttachment(file.getFilename(),file);
127        }
 catch (MessagingException e) {
128            // TODO Auto-generated catch block
129            e.printStackTrace();
130        }

131        mailSender.send(mimeMessage);
132    }

133    public String getFrom() {
134        return from;
135    }

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

139    public String getSubject() {
140        return subject;
141    }

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

145    public String getTo() {
146        return to;
147    }

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

151    public String getTemplateName() {
152        return templateName;
153    }

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

157    public String getContent() {
158        return content;
159    }

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

163    public boolean isValidate() {
164        return validate;
165    }

166    public void setValidate(boolean validate) {
167        this.validate = validate;
168    }

169    public SimpleMailMessage getSimpleMailMessage() {
170        return simpleMailMessage;
171    }

172    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
173        this.simpleMailMessage = simpleMailMessage;
174    }

175}
上面这个类实际上是个发送邮件的工具类,我们只要设置好参数后调用想要的sendXXX()就可以了。如下:

 1 // 注册完马上发送邮件
 2 MailSenderService mailSender = this .getMailsenderService();
 3 mailSender.setTo(form.getEmail());
 4 mailSender.setSubject( " 来自worthtech的邮件 " );
 5 mailSender.setTemplateName( " mail.vm " ); // 设置的邮件模板
 6 Map model = new  HashMap();
 7 model.put( " username " , form.getUserName());
 8 String url = request.getRequestURL().toString();
 9 url = url.substring( 0 , url.lastIndexOf( " / " ));
10 model.put( " url " , url);
11 model.put( " email " " [email protected] " );
12 mailSender.sendWithTemplate(model);
13 System.out.println( " 邮件发送成功! " );

下面的是spring配置

 1 < bean  id ="mailSender"  class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
 2         < property  name ="host"  value ="${mail.host}" />
 3         < property  name ="username"  value ="${mail.username}" />
 4         < property  name ="password"  value ="${mail.password}" />
 5          < property  name ="defaultEncoding"  value ="UTF-8" ></ property >
 6          < property  name ="javaMailProperties" >
 7               < props >
 8                  < prop  key ="mail.smtp.auth" > ${mail.smtp.auth} </ prop >
 9                  < prop  key ="mail.smtp.timeout" > ${mail.smtp.timeout} </ prop >
10                  <!--
11                 <prop key="mail.smtp.starttls.enable">true</prop>
12                 <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
13                 <prop key="mail.smtp.socketFactory.fallback">false</prop>
14                  -->
15              </ props >
16          </ property >
17    </ bean >
18    < bean  id ="simpleMailMessage"  class ="org.springframework.mail.SimpleMailMessage"  singleton ="false" >
19      < property  name ="from" >
20          < value > ${mail.default.from} </ value >
21      </ property >
22    </ bean >
23    < bean  id ="velocityEngine"  class ="org.springframework.ui.velocity.VelocityEngineFactoryBean" >
24          < property  name ="velocityProperties" >    
25              < props >    
26                  < prop  key ="resource.loader" > class </ prop >    
27                  < prop  key ="class.resource.loader.class" >    
28                     org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader   
29                  </ prop >    
30                  < prop  key ="velocimacro.library" ></ prop >    
31              </ props >    
32          </ property >    
33     </ bean >
34      < bean  id ="mailsenderService"  class ="com.worthtech.app.util.MailSenderService" >   
35            < property  name ="mailSender"  ref ="mailSender"   />
36            < property  name ="simpleMailMessage"  ref ="simpleMailMessage"   />
37            < property  name ="velocityEngine"  ref ="velocityEngine"   />
38      </ bean >

mail.vm内容如下:
 1 亲爱的${username}
 2
 3 欢迎加入worthtech! 
 4
 5 当您收到这封信的时候,您已经可以正常登录了。
 6 请点击链接登录首页:${url}
 7 如果您的email程序不支持链接点击,请将上面的地址拷贝至您的浏览器(如IE)的地址栏进入。
 8
 9 如果您还想申请管理员权限,可以联系管理员${email}
10
11 我们对您产生的不便,深表歉意。
12
13 希望您在worthtech度过快乐的时光!
14     
15 -----------------------
16      
17 (这是一封自动产生的email,请勿回复。)

mail.properties如下:
1 mail . host = 218.000 . 000.234
2 mail . port = 25
3 mail . username = gjni @worthtech . net
4 mail . password = xxxxxxxx
5 mail . smtp . auth = true
6 mail . smtp . timeout = 25000
7 mail . default . from = gjni @worthtech . net

你可能感兴趣的:(spring+velocity+javamail发送模板邮件)