Spring提供了發送電子郵件的功能,它向用戶屏蔽了底層郵件系統的一些細節,同時代表客戶端負責底層的資源處理。
Spring的郵件服務支持主要是通過JavaMailSender這個接口實現的:
這是JavaMailSender的接口源代碼(去除注釋),可以看到,主要提供了createMimeMessage和send兩個方法。createMimeMessage方法主要是用來創建JavaMail的MIME信件,而send則是發送電子郵件的主要方法。
Spring中提供了JavaMailSender的簡單實現:org.springframework.mail.javamail.JavaMailSenderImpl。在JavaMailSendImpl這個類中,實現了JavaMailSender中定義的方法的具體實現。而眾所周知,Spring是核心的功能是IOC,所以通過Spring來發送電子郵件,就可以使用Spring強大的IOC功能,下面就來看一下,怎么樣在Spring中發送郵件:
1. Spring配置文件,主要配置mailSender和對velocity的支持
在這個配置文件中,通過propertyConfigurer這個bean加載了郵件的配置文件:mail.properties,這個文件主要定義一些郵件服務的屬性(使用的時候根據自己的要求進行相應的配置,這里以126的smtp服務為例):
下面來看一下MailEngine的實現:
sendMailWithVelocity方法主要是使用Velocity模板文件來發送郵件,Velocity模板文件定義了郵件的內容,模板文件的位置由resourceLoaderPath指定,本例則在classpath下的velocity下,如果是web項目,則位于/WEB-INF/classes/veloticy/目錄下。
執行main方法,就可以發送郵件了。
Spring的郵件服務支持主要是通過JavaMailSender這個接口實現的:
public interface JavaMailSender extends MailSender {
MimeMessage createMimeMessage();
MimeMessage createMimeMessage(InputStream contentStream) throws MailException;
void send(MimeMessage mimeMessage) throws MailException;
void send(MimeMessage[] mimeMessages) throws MailException;
void send(MimeMessagePreparator mimeMessagePreparator) throws MailException;
void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException;
}
MimeMessage createMimeMessage();
MimeMessage createMimeMessage(InputStream contentStream) throws MailException;
void send(MimeMessage mimeMessage) throws MailException;
void send(MimeMessage[] mimeMessages) throws MailException;
void send(MimeMessagePreparator mimeMessagePreparator) throws MailException;
void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException;
}
這是JavaMailSender的接口源代碼(去除注釋),可以看到,主要提供了createMimeMessage和send兩個方法。createMimeMessage方法主要是用來創建JavaMail的MIME信件,而send則是發送電子郵件的主要方法。
Spring中提供了JavaMailSender的簡單實現:org.springframework.mail.javamail.JavaMailSenderImpl。在JavaMailSendImpl這個類中,實現了JavaMailSender中定義的方法的具體實現。而眾所周知,Spring是核心的功能是IOC,所以通過Spring來發送電子郵件,就可以使用Spring強大的IOC功能,下面就來看一下,怎么樣在Spring中發送郵件:
1. Spring配置文件,主要配置mailSender和對velocity的支持
<?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"
default-lazy-init="true" default-autowire="byName">
<!-- 屬性文件加載, 加載郵件設置屬性文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:mail.properties</value>
</list>
</property>
</bean>
<bean id="mailEngine" class="org.example.mailer.MailEngine">
<property name="javaMailSender" ref="javaMailSender" />
<property name="velocityEngine" ref="velocityEngine" />
</bean>
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="classpath:velocity" />
</bean>
<!-- 郵件發送器 -->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="defaultEncoding" value="UTF-8"></property>
<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>
</beans>
<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"
default-lazy-init="true" default-autowire="byName">
<!-- 屬性文件加載, 加載郵件設置屬性文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:mail.properties</value>
</list>
</property>
</bean>
<bean id="mailEngine" class="org.example.mailer.MailEngine">
<property name="javaMailSender" ref="javaMailSender" />
<property name="velocityEngine" ref="velocityEngine" />
</bean>
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="classpath:velocity" />
</bean>
<!-- 郵件發送器 -->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="defaultEncoding" value="UTF-8"></property>
<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>
</beans>
在這個配置文件中,通過propertyConfigurer這個bean加載了郵件的配置文件:mail.properties,這個文件主要定義一些郵件服務的屬性(使用的時候根據自己的要求進行相應的配置,這里以126的smtp服務為例):
mail.from=
mail.host=smtp.126.com
mail.username=
mail.password=
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.host=smtp.126.com
mail.username=
mail.password=
mail.smtp.auth=true
mail.smtp.timeout=25000
下面來看一下MailEngine的實現:
package org.example.mailer;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;
public class MailEngine {
protected final Log logger = LogFactory.getLog(getClass());
private JavaMailSender javaMailSender;
private VelocityEngine velocityEngine;
public void setJavaMailSender(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public void sendMailWithVelocity() {
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg);
String result = null;
Map model = null;
try {
result = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "sendMail.vm", "UTF-8", model);//UTF-8為模板文件的字符編碼
helper.setFrom("郵件發送者");
helper.setSubject("測試Spring郵件");
helper.setTo("郵件接收者");
helper.setText(result);
javaMailSender.send(msg);
} catch (VelocityException e) {
e.printStackTrace();
logger.error(e.getMessage());
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean senaMail() {
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg);
try {
helper.setFrom("郵件發送者");
helper.setSubject("郵件內容");
helper.setTo("郵件接收者");
helper.setText("test spring mailer", true); // 如果發的不是html內容去掉true參數
javaMailSender.send(msg);
} catch (MessagingException e) {
// TODO 自動生成 catch 塊
if (logger.isWarnEnabled()) {
logger.warn("郵件信息導常! 郵件標題為: ");
}
return false;
// e.printStackTrace();
} catch (MailException me) {
// TODO: handle exception
if (logger.isWarnEnabled()) {
logger.warn("發送郵件失敗! 郵件標題為: ");
}
return false;
}
return true;
}
public static void main(String[] args) {
BeanFactory bf = new ClassPathXmlApplicationContext("beans.xml");
MailEngine mailEngine = (MailEngine) bf.getBean("mailEngine");
// mailEngine.senaMail();
mailEngine.sendMailWithVelocity();
}
}
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;
public class MailEngine {
protected final Log logger = LogFactory.getLog(getClass());
private JavaMailSender javaMailSender;
private VelocityEngine velocityEngine;
public void setJavaMailSender(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public void sendMailWithVelocity() {
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg);
String result = null;
Map model = null;
try {
result = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "sendMail.vm", "UTF-8", model);//UTF-8為模板文件的字符編碼
helper.setFrom("郵件發送者");
helper.setSubject("測試Spring郵件");
helper.setTo("郵件接收者");
helper.setText(result);
javaMailSender.send(msg);
} catch (VelocityException e) {
e.printStackTrace();
logger.error(e.getMessage());
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean senaMail() {
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg);
try {
helper.setFrom("郵件發送者");
helper.setSubject("郵件內容");
helper.setTo("郵件接收者");
helper.setText("test spring mailer", true); // 如果發的不是html內容去掉true參數
javaMailSender.send(msg);
} catch (MessagingException e) {
// TODO 自動生成 catch 塊
if (logger.isWarnEnabled()) {
logger.warn("郵件信息導常! 郵件標題為: ");
}
return false;
// e.printStackTrace();
} catch (MailException me) {
// TODO: handle exception
if (logger.isWarnEnabled()) {
logger.warn("發送郵件失敗! 郵件標題為: ");
}
return false;
}
return true;
}
public static void main(String[] args) {
BeanFactory bf = new ClassPathXmlApplicationContext("beans.xml");
MailEngine mailEngine = (MailEngine) bf.getBean("mailEngine");
// mailEngine.senaMail();
mailEngine.sendMailWithVelocity();
}
}
sendMailWithVelocity方法主要是使用Velocity模板文件來發送郵件,Velocity模板文件定義了郵件的內容,模板文件的位置由resourceLoaderPath指定,本例則在classpath下的velocity下,如果是web項目,則位于/WEB-INF/classes/veloticy/目錄下。
執行main方法,就可以發送郵件了。