spring实现邮件发送

spring实现邮件发送(简单版)

用spring实现邮件发送除了需要spring的包之外还需要额外的两个包,以下是官网文档上面的原话:

The following additional jars to be on the classpath of your application in order to be able to use the Spring Framework's email library.

  • The JavaMail mail.jar library

  • The JAF activation.jar library

同时还需要spring的的一个支持包,在这个demo中我用的spring3.2 release版

spring-context-support-3.2.0.RELEASE.jar

首先在application.xml中配置邮件发送服务器:

<!-- mail start -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="smtp.163.com" /> <!-- 配置邮件服务器-->
		<property name="username" value="[email protected]"></property><!-- 配置发送邮件的邮箱-->
 		<property name="password" value="????"></property><!-- 配置邮箱密码-->
		<property name="defaultEncoding" value="utf-8"></property><!-- 配置默认编码-->
		<property name="javaMailProperties">
			<props>
				 <prop key="mail.smtp.auth">true</prop> <!--如果邮箱需要密码这个地方必须为true -->
			</props>
		</property>
	</bean>

	<!-- this is a template message that we can pre-load with default state -->
	<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
		<property name="from" value="[email protected]" />
		<property name="subject" value="谢谢" />
	</bean>
	<!-- mail end -->

 配置邮件发送的类和接口

public class EmailManagerImpl implements EmailManager {

	@Autowired
	@Qualifier("mailSender")
    private MailSender mailSender;
	
	@Autowired
	@Qualifier("templateMessage")
    private SimpleMailMessage templateMessage;

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

    public void setTemplateMessage(SimpleMailMessage templateMessage) {
        this.templateMessage = templateMessage;
    }

    public void sendMail() {
        SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
        msg.setTo("[email protected]");
        msg.setText(
            "Dear" + ", 谢谢你注册我们的网站! ");
        try{
            this.mailSender.send(msg);
        }
        catch(MailException ex) {
            // simply log it and go on...
            System.err.println(ex.getMessage());
        }
    }

 之后在需要的地方调用sendMail()方法就好了。

 

猜你喜欢

转载自huhongyu.iteye.com/blog/1773336
今日推荐