发送邮件

1.通过eclipse建立Java Project,新建lib文件夹,放入需要的jar包,添加至classpath。如下所示

2.新建applicationContext.xml文件。内容如下。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    
    <bean id="mailService" class="org.daniel.send.MailService">
        <property name="mailSender" ref="mailSender"></property>
    </bean>
    
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.163.com" />
        <property name="port" value="25" />
        <property name="username" value="zhangsan@163.com" />
        <property name="password" value="zhangsan" />
    </bean>
</beans>

 

3.新建MailService.java。内容如下。 

package org.daniel.send;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.util.Assert;

/**
 * 邮件发送服务类。
 * 
 * @author daniel
 * @date 2013-11-20
 * @since 0.1
 * @version 0.1
 */
public class MailService implements InitializingBean {
    private MailSender mailSender;

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

    /**
     * 发送邮件
     */
    public void sendEmail() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("zhangsan@163.com");
        simpleMailMessage.setTo("zhangsan@163.com");
        simpleMailMessage.setSubject("测试 邮件");
        simpleMailMessage.setText("亲爱的先生/女士:\n这是测试邮件,请勿回复!");
        try {
            mailSender.send(simpleMailMessage);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(mailSender, "注入mailSender失败");

    }
}

4.编写单元测试类MailServiceTest.java。内容如下。

package org.daniel.send;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * 邮件发送服务单元测试类。
 * 
 * @author danile
 * @since 0.1
 * @version 0.1
 * 
 */
public class MailServiceTest {
    private static ApplicationContext ctx;

    @BeforeClass
    public static void getCtx() {
        ctx =  new ClassPathXmlApplicationContext("applicationContext.xml");
    }
    @Test
    public void sendEmail() {
        MailService mailService = (MailService) ctx.getBean("mailService");
        mailService.sendEmail();
    }
    
}

 

 

 

 

 

 

posted @ 2013-11-20 21:13  hntyzgn  阅读(202)  评论(0编辑  收藏  举报