1、Spring的配置文件:
<?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"></property>
<property name="username" value="test@163.com"></property>
<property name="password" value="123456"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
<prop key="mail.smtp.port">465</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
</props>
</property>
</bean>
</beans>
2、应用:
package com.text.springEmail;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
public class MainTest{
public static void main(String[] args){
System.out.println("Test start.");
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
JavaMailSender sender = (JavaMailSender)context.getBean("mailSender");//获取JavaMailSender bean
SimpleMailMessage mail = new SimpleMailMessage(); //注意SimpleMailMessage只能用来发送text格式的邮件</span>
mail.setTo("test1@163.com");//接受者
mail.setFrom("test2@163.com");//发送者,这里还可以另起Email别名,不用和xml里的username一致
mail.setSubject("spring邮件发送测试");//主题
mail.setText("邮件发送成功!");//邮件内容
sender.send(mail);//发送邮件
System.out.print("Test end..");
}
}
3、所需jar包
这里spring的jar包,我就不说了,只说一下spring发送邮件所需要的jar:activation.jar、mail.jar