必须添加的包commons-logging.jar,mail.jar,spring.jar
mailMessage.xml配置文件********************************
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns=" " xmlns:xsi=" " xsi:schemaLocation=" " xmlns:aop=" " xmlns:p=" "> <!-- 加载Properties文件 --> <bean id="configurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:mail.properties</value> </list> </property> </bean> <!-- 申明SimpleMailMessage对象 --> <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="from"> <!-- 设置发送方,hz是发送者的名字 --> <value><![CDATA[hz<${mail.from}>]]></value> </property> <!-- 设置接收方 --> <property name="to" value="${mail.to}" /> <!-- 查看SimpleMailMessage源码还可以注入标题,内容等 --> </bean> <!-- 申明JavaMailSenderImpl对象 --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="defaultEncoding" value="UTF-8" /> <property name="host" value="${mail.host}" /> <property name="username" value="${mail.username}" /> <property name="password" value="${mail.password}" /> <property name="javaMailProperties"> <props> <!-- 设置认证开关 --> <prop key="mail.smtp.auth">true</prop> <!-- 启动调试开关 --> <prop key="mail.debug">true</prop> </props> </property> </bean> </beans>
mail.properties************************
mail.host=smtp.163.com//走163发送协议 mail.username=xxxxxxxx//163邮箱名
mail.password=xxxxxxxx//163邮箱密码
发送者邮箱 这里就是163邮箱 接受者邮箱
测试文件***********************
package mail;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage;
public class SpringSimpleMailTest { public static void main(String[] args) { ApplicationContext actx = new ClassPathXmlApplicationContext( "mail/mailMessage.xml"); MailSender ms = (MailSender) actx.getBean("mailSender"); SimpleMailMessage smm = (SimpleMailMessage) actx.getBean("mailMessage"); // 主题,内容 smm.setSubject("你好"); smm.setText("这个是一个通过Spring框架来发送邮件的小程序"); ms.send(smm); } }