spring javamail 使用

1  xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "spring-beans.dtd" >
<beans>
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host">
			<value>smtp.163.com</value>
		</property>
		<property name="javaMailProperties">
			<props>
				<!-- 如果要使用用户名和密码验证,这一步需要 -->
				<prop key="mail.smtp.auth">true</prop>
			</props>
		</property>
		<property name="username">
			<value>邮箱的用户名ceshiyouxiang2</value>
		</property>
		<property name="password">
			<value>邮箱的密码</value>
		</property>
	</bean>

	<!-- 简单的message -->

	<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
		<property name="to">
			<value>邮件是发给谁的[email protected]</value>
		</property>

		<property name="from">
			<value>邮箱是来自哪里的[email protected]</value>

		</property>
		<property name="subject"> <!-- Email 标题 -->
			<value>邮件的主题是什么?A Spring Mail sender,测试 测试</value>
		</property>
	</bean>

	<!-- 测试发送的类 -->
	<bean id="testMailSender" class="com.ambow.mailtest.TestSenderMail">
		<property name="mailMessage">
			<ref bean="mailMessage" />
		</property>

		<property name="mailSender">
			<ref bean="mailSender" />
		</property>
	</bean>
</beans>

2  spring 发送email信息的类

  

import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class TestSenderMail {
	
	private MailSender mailSender;
	private SimpleMailMessage mailMessage;
 
	public void sendMail() {
		
		SimpleMailMessage message = new SimpleMailMessage(mailMessage);
		// 设置email内容,
		message.setText("测试Spring 发送Email.");
		message.setTo( "[email protected]");
		
		try {
			mailSender.send(message);
			System.out.println( " 发送成功!!!");
		} catch (MailException e) {
			// TODO Auto-generated catch block
			System.out.println("email  . 发送Email失败了....");
			e.printStackTrace();
		}
	}
	
	
	
	
	public MailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(MailSender mailSender) {
		this.mailSender = mailSender;
	}

	public SimpleMailMessage getMailMessage() {
		return mailMessage;
	}

	public void setMailMessage(SimpleMailMessage mailMessage) {
		this.mailMessage = mailMessage;
	}
}

3 测试启动

  

public static void main(String[] args) {

		
		ClassPathResource res = new ClassPathResource("spring/applicationContext-mail.xml");
		XmlBeanFactory factory = new XmlBeanFactory(res);
		
		TestSenderMail testSenderMail = (TestSenderMail) factory.getBean("testMailSender");
		
		testSenderMail.sendMail();	
	}

相关推荐