使用Spring简化JavaMail

如果你用过用javax.mail来写email发送,你就会发现这个包写得如此繁杂。

import java.util.Date;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class JavaMailDemo {
    public static void main(String[] args) {
        Properties p =new Properties();
        //首先指定发送邮件的主机
        String host="127.0.0.1";
        p.put("mail.smtp.host", host);
        //得到发送邮件的sessoin
        Session session =Session.getDefaultInstance(p);
        //准备一封电子邮件
        Message ms =new MimeMessage(session);
        Address address =null;
        Address to=null; //收件人地址
        try {
            address=new InternetAddress("pengzj");
        ms.setFrom(address);
        to=new InternetAddress("[email protected]");
        ms.setRecipient(Message.RecipientType.TO, to);
        ms.setSubject("javamail测试2");
        ms.setSentDate(new Date());
        ms.setText("你好,这是javamail发送的电子邮件2");
        Transport t= session.getTransport("smtp");
        t.send(ms);
        System.out.println("邮件已发送");
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

一个地址都要如此封装,真是麻烦。

Spring的初衷就是要让JavaEE技术变得容易使用。

那么它对JavaMail的支持也是理所当然的了。下面我们来看看如何使用Spring+Javamail.

首先配置好spring的application.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>127.0.0.1</value>
</property>

</bean>
</beans>

发送邮件的代码变得如此简单:

package com.pengzj.mail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

public class MyMailSender {

    public static void main(String[] args) {
        ApplicationContext ctx =new ClassPathXmlApplicationContext("applicationContext.xml");
        JavaMailSender sender=(JavaMailSender)ctx.getBean("mailSender");
        SimpleMailMessage sms =new SimpleMailMessage();
        sms.setFrom("[email protected]");
        sms.setTo("[email protected]");
        sms.setText("这是用spring发送的电子邮件");
        sms.setSubject("how are you!");
        sender.send(sms);
    }
}

你可能感兴趣的:(spring,职场,mail,javamail,休闲)