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

Java代码 复制代码 收藏代码
  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. }  
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()就可以了。如下:

Java代码 复制代码 收藏代码
  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""gjni@worthtech.net");  
  12. mailSender.sendWithTemplate(model);  
  13. System.out.println("邮件发送成功!");  
//注册完马上发送邮件
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", "gjni@worthtech.net");
mailSender.sendWithTemplate(model);
System.out.println("邮件发送成功!");

下面的是spring配置

Java代码 复制代码 收藏代码
  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>  
<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内容如下:

Java代码 复制代码 收藏代码
  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,请勿回复。)  
亲爱的${username}

欢迎加入worthtech! 

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

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

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

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

mail.properties如下:

Java代码 复制代码 收藏代码
  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