spring对电子邮件的支持

spring的配置

 

<context:property-placeholder location="classpath:mail.properties"/>
	
	<!-- 配置spring提供的邮件发送工具类 -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	  <property name="host" value="${mail.smtp.host}"/>
	  <property name="username" value="${mail.user}"/>
	  <property name="password" value="${mail.password}"/>
	  <property name="javaMailProperties">
	    <props>
	       <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>      
	       <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>      
	    </props>      
	  </property>
	</bean>
	
	<!-- 配置邮件消息的模板类 -->
	<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
	  <property name="from" value="${mail.user}"/>
	  <property name="subject" value="这是用Spring发送的一封电子邮件"/>
	  <property name="text" value="这是邮件内容"/>
	</bean>

 

mail.properties

 

#邮件发送服务器地址: smtp.126.com
mail.smtp.host=smtp.163.com
#是否需要安全验证。"true"或"false"
mail.smtp.auth=true
mail.smtp.timeout=2000
#用户名,密码等信息
[email protected]
mail.password=8888888

 

测试类

public class SendMailTest {
	private static ApplicationContext context;
	
	@BeforeClass
	public static void init() {
		context = new ClassPathXmlApplicationContext("app*.xml");
	}

	@Test
	public void testSendTxtMail(){
		MailSender sender = context.getBean("mailSender", MailSender.class);
		SimpleMailMessage msg = context.getBean("templateMessage", SimpleMailMessage.class);
		msg.setTo("[email protected]");
		msg.setText("你好吗??");
		sender.send(msg);
	}
}

 

 

你可能感兴趣的:(spring)