JavaMail与Spring集成开发

  1. spring框架集成JavaMail的主要包

    wKiom1nCAtrgYnbOAACOw8NSxuI820.png

2.mail.properties

1
2
3
4
5
mail.smtp.host=smtp. 163 .com
mail.smtp.auth= true
mail.username= 15511111111
mail.password= 123
mail.from= 15511111111 @163 .com

3.使用spring配置(applicationContext-mail.xml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?xml version= "1.0"  encoding= "UTF-8" ?>
<beans xmlns= "http://www.springframework.org/schema/beans"  
     xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"       
     xmlns:p= "http://www.springframework.org/schema/p"  
     xmlns:context= "http://www.springframework.org/schema/context"   
     xmlns:tx= "http://www.springframework.org/schema/tx"  
     xmlns:aop= "http://www.springframework.org/schema/aop"  
     xsi:schemaLocation="http: //www.springframework.org/schema/beans    
     http: //www.springframework.org/schema/beans/spring-beans.xsd    
     http: //www.springframework.org/schema/aop    
     http: //www.springframework.org/schema/aop/spring-aop.xsd    
     http: //www.springframework.org/schema/tx    
     http: //www.springframework.org/schema/tx/spring-tx.xsd    
     http: //www.springframework.org/schema/context    
     http: //www.springframework.org/schema/context/spring-context.xsd">
     
     <description>JavaMail配置文件</description>
     
     <!-- 加载mail.properties文件 -->
     <context:property-placeholder location= "classpath:mail.properties" />
     
     
     <!-- 配置一个简单邮件对象 -->
     <bean id= "mailMessage"  class = "org.springframework.mail.SimpleMailMessage" >
        <property name= "from"  value= "${mail.from}" ></property>
     </bean>
     
     <!-- 邮件的发送对象 -->
     <bean id= "mailSender"  class = "org.springframework.mail.javamail.JavaMailSenderImpl" >
          <property name= "host"  value= "${mail.smtp.host}" ></property>
          <property name= "username"  value= "${mail.username}" ></property>
          <property name= "password"  value= "${mail.password}" ></property>
          <property name= "defaultEncoding"  value= "UTF-8" ></property>
          <!-- 邮件发送相关的配置信息 -->
          <property name= "javaMailProperties"  >
             <props>
                   <prop key= "mail.smtp.auth" >${mail.smtp.auth}</prop>
                   <prop key= "mail.debug" > true </prop>
                   <prop key= "mail.smtp.timeout" > 0 </prop>
             </props>
          </property>
     </bean>
</beans>

4.发送简单邮件代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public  void  testJavaMail()  throws  Exception{
     ApplicationContext ac =  new  ClassPathXmlApplicationContext( "classpath:applicationContext-mail.xml" );
         
     SimpleMailMessage message = (SimpleMailMessage) ac.getBean( "mailMessage" ); //加载简单邮件对象
     JavaMailSender sender = (JavaMailSender) ac.getBean( "mailSender" );        //得到邮件的发送对象,专门用于邮件发送
         
     //设置简单邮件对象的属性
     message.setSubject( "spring与javamail的测试" ); //主题
     message.setText( "hello,spring and javamail " ); //内容
     message.setTo( "174111111@qq.com" ); //收件箱
         
     //发送邮件
     sender.send(message);
}

5.发送带有图片和带附件的邮件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public  void  testJavaMail()  throws  Exception{
     ApplicationContext ac =  new  ClassPathXmlApplicationContext( "classpath:applicationContext-mail.xml" );
         
         
     JavaMailSender sender = (JavaMailSender) ac.getBean( "mailSender" );        //得到邮件的发送对象,专门用于邮件发送
         
//发送一个允许带图片,同时带附件的邮件
     MimeMessage message = sender.createMimeMessage(); //创建一封允许带图片,同时带附件的邮件对象
         
        //为了更好的操作MimeMessage对象,借用一个工具类来操作它
     MimeMessageHelper helper =  new  MimeMessageHelper(message,  true );
         
     //通过工具类设置主题,内容,图片,附件
     helper.setFrom( "155111111111@163.com" );
     helper.setTo( "17411111@qq.com" );
     helper.setSubject( "这是来自x网的一个请求" );
     helper.setText( "<html><head></head><body><h1>hello!!baby </h1>"
                     + "<a href=http://www.baidu.com>去百度</a>"     "<img src=cid:image/></body></html>" , true );//第二个参数说明内容要解析为html代码
         
     //添加图片
     FileSystemResource resource =  new  FileSystemResource( new  File( "E:\\原理分析.png" ));
     helper.addInline( "image" , resource);
         
     sender.send(message);
         
     /*JavaMailSenderImpl mailSender = (JavaMailSenderImpl) ac.getBean("mailSender");
         
     //3.创建一封允许带附件的邮件对象
     MimeMessage mimeMessage = mailSender.createMimeMessage();//创建出允许带附件的邮件对象
         
         
     //4.创建出一个用于操作MimeMessage的帮助类的对象
     MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
         
     //5.设置邮件的相关内容 (发送者,拼接者,主题,内容 )
     helper.setFrom("15511111@163.com");
     helper.setTo("174@qq.com");
     helper.setSubject("带图片和附件的邮件测试");
     helper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>"
                        +"<a href=http://www.itheima.com>去百度</a>"    + "<img src=cid:image/></body></html>", true);//cid:是固定的,后面的image是自己定义的
         
     //指定image所在的位置(是指本地电脑)
     FileSystemResource img = new FileSystemResource(new File("E:/原理分析.png"));//将本地的图片转化成一个图片资源 
     helper.addInline("image", img);//image的参数来自上面cid的取值
         
     //发送时带附件
     FileSystemResource zipResource = new FileSystemResource(new File("E:/javamail1_4_4.zip"));
     helper.addAttachment("javamail1_4_4.zip", zipResource);*/
         
      //发送邮件
     //mailSender.send(mimeMessage);
         
         
}


项目中使用spring中的JavaMail工具类

01.需要在类中注入相关对象

1
2
3
4
5
6
7
8
private  SimpleMailMessage mailMessage;
private  JavaMailSender mailSender;
public  void  setMailMessage(SimpleMailMessage mailMessage) {
     this .mailMessage = mailMessage;
}
public  void  setMailSender(JavaMailSender mailSender) {
     this .mailSender = mailSender;
}

02.在spring配置文件中配置

1
2
3
4
5
<bean id= "userService"  class = "com.my.qb.service.impl.UserServiceImpl" >
         <property name= "baseDao"  ref= "baseDao" ></property>
         <property name= "mailMessage"  ref= "mailMessage" ></property>
         <property name= "mailSender"  ref= "mailSender" ></property>
     </bean>


03.实现功能(比如:在注册的时候,发送邮件,邮件可能发送不成功,但要保证注册完成)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 新增用户
*/
public  void  saveOrUpdate( final  User entity) {
     if (UtilFuns.isEmpty(entity.getId())){
         //新增
         String id = UUID.randomUUID().toString();
         entity.setId(id);
         entity.getUserinfo().setId(id);
             
         //补充Shiro添加后的bug
         entity.setPassword(Encrypt.md5(SysConstant.DEFAULT_PASS, entity.getUserName()));
             
         baseDao.saveOrUpdate(entity); //记录保存
             
         //独立的比较费时的,都交给线程来做
         //spring集成javaMail
         Thread th =  new  Thread( new  Runnable() {
             public  void  run() {
                 try  {
                     mailMessage.setTo(entity.getUserinfo().getEmail());
                     mailMessage.setSubject( "新员工入职的系统账户通知" );
                     mailMessage.setText( "欢迎您加入本集团,您的用户名:" +entity.getUserName()+ ",初始密码:" +SysConstant.DEFAULT_PASS);
                         
                     mailSender.send(mailMessage);
                 catch  (Exception e) {
                     e.printStackTrace();
                 }
             }
         });
             
         th.start();
             
             
     } else {
         //修改
         baseDao.saveOrUpdate(entity);
     }
         
}