Spring发送电子邮件

   Spring提供了发送电子邮件的功能,它向用户屏蔽了底层邮件系统的一些细节,同时代表客户端负责底层的资源处理。

Spring的邮件服务支持主要是通过JavaMailSender这个接口实现的:

public   interface  JavaMailSender  extends  MailSender {

    MimeMessage createMimeMessage();

    MimeMessage createMimeMessage(InputStream contentStream)  throws  MailException;

     void  send(MimeMessage mimeMessage)  throws  MailException;

     void  send(MimeMessage[] mimeMessages)  throws  MailException;

     void  send(MimeMessagePreparator mimeMessagePreparator)  throws  MailException;

     void  send(MimeMessagePreparator[] mimeMessagePreparators)  throws  MailException;

}

 

这是JavaMailSender的接口源代码(去除注释),可以看到,主要提供了createMimeMessage和send两个方法。createMimeMessage方法主要是用来创建JavaMail的MIME信件,而send则是发送电子邮件的主要方法。

Spring中提供了JavaMailSender的简单实现:org.springframework.mail.javamail.JavaMailSenderImpl。在JavaMailSendImpl这个类中,实现了JavaMailSender中定义的方法的具体实现。而众所周知,Spring是核心的功能是IOC,所以通过Spring来发送电子邮件,就可以使用Spring强大的IOC功能,下面就来看一下,怎么样在Spring中发送邮件:

1. Spring配置文件,主要配置mailSender和对velocity的支持

<? xml version="1.0" encoding="UTF-8" ?>

< beans  xmlns ="http://www.springframework.org/schema/beans"

    xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"

    default-lazy-init ="true"  default-autowire ="byName" >

     <!--  属性文件加载, 加载邮件设置属性文件  -->

     < bean  id ="propertyConfigurer"

        class ="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >

         < property  name ="locations" >

             < list >

                 < value > classpath:mail.properties </ value >

             </ list >

         </ property >

     </ bean >

     < bean  id ="mailEngine"  class ="org.example.mailer.MailEngine" >

         < property  name ="javaMailSender"  ref ="javaMailSender"   />

         < property  name ="velocityEngine"  ref ="velocityEngine"   />

     </ bean >

     < bean  id ="velocityEngine"

        class ="org.springframework.ui.velocity.VelocityEngineFactoryBean" >

         < property  name ="resourceLoaderPath"  value ="classpath:velocity"   />

     </ bean >

     <!--  邮件发送器  -->

     < bean  id ="javaMailSender"  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 >

             </ props >

         </ property >

     </ bean >

</ beans >

 

在这个配置文件中,通过 propertyConfigurer这个bean 加载了邮件的配置文件:mail.properties,这个文件主要定义一些邮件服务的属性(使用的时候根据自己的要求进行相应的配置,这里以126的smtp服务为例):

mail.from =

mail.host = smtp. 126 .com

mail.username =

mail.password =

mail.smtp.auth = true

mail.smtp.timeout = 25000

 

下面来看一下MailEngine 的实现:

package  org.example.mailer;

import  java.util.Map;

import  javax.mail.MessagingException;

import  javax.mail.internet.MimeMessage;

import  org.apache.commons.logging.Log;

import  org.apache.commons.logging.LogFactory;

import  org.apache.velocity.app.VelocityEngine;

import  org.apache.velocity.exception.VelocityException;

import  org.springframework.beans.factory.BeanFactory;

import  org.springframework.context.support.ClassPathXmlApplicationContext;

import  org.springframework.mail.MailException;

import  org.springframework.mail.javamail.JavaMailSender;

import  org.springframework.mail.javamail.MimeMessageHelper;

import  org.springframework.ui.velocity.VelocityEngineUtils;

public   class  MailEngine {

     protected   final  Log logger  =  LogFactory.getLog(getClass());

     private  JavaMailSender javaMailSender;

     private  VelocityEngine velocityEngine;

     public   void  setJavaMailSender(JavaMailSender javaMailSender) {

         this .javaMailSender  =  javaMailSender;

    }

     public   void  setVelocityEngine(VelocityEngine velocityEngine) {

         this .velocityEngine  =  velocityEngine;

    }

     public   void  sendMailWithVelocity() {

        MimeMessage msg  =  javaMailSender.createMimeMessage();

        MimeMessageHelper helper  =   new  MimeMessageHelper(msg);

        String result  =   null ;

        Map model  =   null ;

         try  {

            result  =  VelocityEngineUtils.mergeTemplateIntoString(

                    velocityEngine,  " sendMail.vm " ,  " UTF-8 " , model); // UTF-8为模板文件的字符编码

            helper.setFrom( " 邮件发送者 " );

            helper.setSubject( " 测试Spring邮件 " );

            helper.setTo( " 邮件接收者 " );

            helper.setText(result);

            javaMailSender.send(msg);

        }  catch  (VelocityException e) {

            e.printStackTrace();

            logger.error(e.getMessage());

        }  catch  (MessagingException e) {

             //  TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

     public   boolean  senaMail() {

        MimeMessage msg  =  javaMailSender.createMimeMessage();

        MimeMessageHelper helper  =   new  MimeMessageHelper(msg);

         try  {

            helper.setFrom( " 邮件发送者 " );

            helper.setSubject( " 邮件内容 " );

            helper.setTo( " 邮件接收者 " );

            helper.setText( " test spring mailer " ,  true );  //  如果发的不是html内容去掉true参数

            javaMailSender.send(msg);

        }  catch  (MessagingException e) {

             //  TODO 自动生成 catch 块

             if  (logger.isWarnEnabled()) {

                logger.warn( " 邮件信息导常! 邮件标题为:  " );

            }

             return   false ;

             //  e.printStackTrace();

        }  catch  (MailException me) {

             //  TODO: handle exception

             if  (logger.isWarnEnabled()) {

                logger.warn( " 发送邮件失败! 邮件标题为:  " );

            }

             return   false ;

        }

         return   true ;

    }

     public   static   void  main(String[] args) {

        BeanFactory bf  =   new  ClassPathXmlApplicationContext( " beans.xml " );

        MailEngine mailEngine  =  (MailEngine) bf.getBean( " mailEngine " );

         //  mailEngine.senaMail();

        mailEngine.sendMailWithVelocity();

    }

}

 

sendMailWithVelocity方法主要是使用Velocity模板文件来发送邮件,Velocity模板文件定义了邮件的内容,模板文件的位置由 resourceLoaderPath 指定,本例则在classpath下的velocity下,如果是web项目,则位于/WEB-INF/classes/veloticy/目录下。

执行main方法,就可以发送邮件了。

原文地址:https://www.cnblogs.com/moonfans/p/3362620.html