spring mail发送邮件实例

spring mail发送邮件实例
Spring提供了一个发送电子邮件的高级抽象层,它向用户屏蔽了底层邮件系统的一些细节,同时负责低层次的代表客户端的资源处理。Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender和 封装了简单邮件的属性如from, to,cc, subject, text的值对象叫做SimpleMailMessage。
下面以发送简单邮件为例说明邮件发送功能的实现过程。
1.用spring的mail发邮件需要将j2ee包里的mail.jar和spring.jar两个包引入到项目中。
2.邮件发送类

package  com;

import  javax.servlet.ServletException;

import  org.springframework.context.ApplicationContext;
import  org.springframework.context.support.ClassPathXmlApplicationContext;
import  org.springframework.mail.SimpleMailMessage;
import  org.springframework.mail.javamail.JavaMailSender;

public   class  SendMail {
    
public  ApplicationContext ctx  =   null ;
    
    
public  SendMail(){
        ctx 
=   new  ClassPathXmlApplicationContext( " applicationContext.xml " ); // 获取上下文
    }
    
    
/**
     * 发送简单邮件
     
*/
    
public   void  sendMail1(){
        JavaMailSender sender 
=  (JavaMailSender) ctx.getBean( " mailSender " ); // 获取JavaMailSender bean
        SimpleMailMessage mail  =   new  SimpleMailMessage();
        
try  {
            mail.setTo(
" [email protected] " ); // 接受者
            mail.setFrom( " [email protected] " ); // 发送者
            mail.setSubject( " spring mail test! " ); // 主题
            mail.setText( " springMail 的简单发送测试 " ); // 邮件内容
            sender.send(mail);
        } 
catch  (Exception e) {
            e.printStackTrace();
        }
    }
    
    
/**
     * 主测试方法
     
*/
    
public   static   void  main(String[] args)  throws  ServletException{
        
new  SendMail().sendMail1();
    }
}
3.最后的就是配置ApplicationContext.xml文件的内容:
<? xml version = " 1.0 "  encoding = " UTF-8 " ?>
<! DOCTYPE beans PUBLIC  " -//SPRING//DTD BEAN//EN "   " http://www.springframework.org/dtd/spring-beans.dtd " >

<!--  注意:这里的参数(如用户名、密码)都是针对邮件发送者的  -->
< beans >
    
< bean id = " mailSender "
        
class = " org.springframework.mail.javamail.JavaMailSenderImpl " >
        
< property name = " host " >
            
< value > smtp. 163 .com </ value >
        
</ property >
        
< property name = " javaMailProperties " >
            
< props >
                
< prop key = " mail.smtp.auth " > true </ prop >
                
< prop key = " mail.smtp.timeout " > 25000 </ prop >
            
</ props >
        
</ property >
        
< property name = " username " >
            
< value > xxxxxxx </ value >
        
</ property >
        
< property name = " password " >
            
< value > xxxxxxx </ value >
        
</ property >
    
</ bean >
</ beans >

你可能感兴趣的:(spring mail发送邮件实例)