springframework 发送邮件
邮件功能对于web应用的重要性是不言而喻的,那么如何实现就成了一个不小的问题,还好spring为我们解决了这个问题,下面就是具体的实现:
首先导入一下两个包:
org.springframework:spring-context-support:4.3.1.RELEASE
javax.mail:mail:1.4.6
其次创建 mail-config.properties 文件:
mail.host = smtp.xxxxx.com
mail.username = xxxxxxx
mail.password = xxxxxx
mail.port = 25
**之后就是配置 applicationContext.xml **:
(1) 在xml中引入mail-config.properties:
<bean id="configurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:mail-config.properties</value>
</list>
</property>
</bean>
(2) 配置mail:
<bean id="mailSender" 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="port" value="${mail.port}"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
**下面就是具体的实现了 **:
@Service
public class MailService {
@Resource
private MailSender mailSender;
public void sendMessage(String[] to,String subject,String text){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(text);
mailSender.send(simpleMailMessage);
}
}
好了,大功告成!