1、Spring发送邮件依赖于JavaMail和JAF的两个库文件:mail.jar和activation.jar
2、Spring提供的发送电子邮件的高级抽象层,向用户屏蔽了底层邮件系统的一些细节,同时代表客户端负责底层资源的处理
3、MailSender和SimpleMailMessage的基本用法:
首先定义一个借口:
package com.mail.service; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 12-6-12 * Time: 下午3:37 * To change this template use File | Settings | File Templates. */ public interface OrderManager { void placeOrder() ; }
实现类:
package com.mail.sender; import com.mail.demo.Order; import com.mail.service.OrderManager; import org.springframework.mail.MailException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 12-6-12 * Time: 下午3:39 * To change this template use File | Settings | File Templates. */ public class SimpleOrderManager implements OrderManager { private MailSender mailSender ; private SimpleMailMessage simpleMailMessage ; public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) { this.simpleMailMessage = simpleMailMessage; } public void placeOrder() { SimpleMailMessage simpleMailMessage1 = new SimpleMailMessage(this.simpleMailMessage); //SimpleMailMessage只能用来发送text格式的邮件 simpleMailMessage1.setTo("[email protected]"); simpleMailMessage1.setText("hello,world"); try{ this.mailSender.send(simpleMailMessage1); } catch (MailException e){ System.out.println(e.getMessage()); } } }
实现类完成了,要注入他的两个属性MailSender和SimpleMailMessage,配置如下:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.qq.com"/> <property name="defaultEncoding" value="UTF-8"/> <property name="username" value="[email protected]"/> <property name="password" value="XXXXX"/> <property name="javaMailProperties"> <value> mail.smtp.auth=true </value> </property> </bean>
这里是mailSender的注入,MailSender是发送邮件的主要接口,Spring为它提供的一个子接口,即:org.springframework.mail.javamail.JavaMailSender,在他的实现类中有用来发送邮件的一些配置:
host是邮箱的host,这里的是qq,username是发邮件的邮箱账号,password是密码等属性
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="from" value="[email protected]"/> <property name="subject" value="welcome"/> </bean>
SimpleMailMessage是值对象,封装了一些简单的属性,如from、to、subject、text等等,SimpleMailMessage只能用来发送text格式的邮件
注入SimpleOrderMessage对象:
<bean id="orderManager" class="com.mail.sender.SimpleOrderManager"> <property name="mailSender" ref="mailSender"/> <property name="simpleMailMessage" ref="templateMessage"/> </bean>
来测试一下:
public class MailTest { @Test public void main1(){ BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml") ; SimpleOrderManager simpleOrderManager = (SimpleOrderManager) beanFactory.getBean("orderManager"); simpleOrderManager.placeOrder(); } }
运行一下就会看到邮件