Spring配置邮件服务
(1)配置邮件发送服务器
方法1:显示的配置SMTP邮件服务器
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>mail.springinaction.com</value>
</property>
</bean>
默认使用25端口,也可以使用JavaMailSenderImpl的port属性自定义端口
方法2:使用jndi中配置的mailsession
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="session">
<ref bean="mailsession"/>
</property>
</bean>
<bean id="mailsession" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/mail/Session</value>
</property>
</bean>
(2)配置邮件模板,以便不用填写主题,发送人,接受人等信息
<bean id="enrollmentMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="to">
<value>coursedirector@springincation.com</value>
</property>
<property name="from">
<value>administrator@springincation.com</value>
</property>
<property name="subject">
<value>course information</value>
</property>
</bean>
(3)配置服务
<bean id="mailService" class="com.springinaction.training.MailServiceImple">
<property name="mailMessage">
<ref bean="enrollmentMailMessage"/>
</property>
<property name="mailSender">
<ref bean="mailSender"/>
</property>
</bean>
(4)应用
首先得到mailService,其中包包括mailMessage和mailSender属性
StringBuffer sb=new StringBuffer();
sb.append("mail body");
message.setText(sb.toString());
try{
mailSender.send(message);
}catch(MailException e){
}