许多业务场景下需要给用户发送邮件,例如注册、重置密码等,Spring提供 JavaMailSender接口实现邮件发送。
本文对JavaMailSender用法做个简单的小结。
1. maven依赖
在pom.xml中添加如下依赖:
<properties>
<springframework.version>4.3.6.RELEASE</springframework.version>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
2.applicationContext.xml
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:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!--javaMailSender-->
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="465"/>
<property name="username" value="xxx@gmail.com"/>
<property name="password" value="xxx"/>
<property name="defaultEncoding" value="UTF-8" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
</beans>
3.测试代码
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.mail.internet.MimeMessage;
import java.io.File;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class JavaMailSenderTest {
@Autowired
private JavaMailSender javaMailSender;
@Test
public void testSimpleTextMail(){ //发送普通文本邮件
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom("FX_SKY");// 发送者,可选的
mailMessage.setTo("ricky_feng@163.com");//接受者
mailMessage.setSubject("测试邮件");//主题
mailMessage.setText("Test Email send by javaMailSender!");//邮件内容
javaMailSender.send(mailMessage);
}
@Test
public void testMimeMail() throws Exception { //发送HTML格式的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("FX_SKY");
helper.setTo("ricky_feng@163.com");
helper.setSubject("主题:嵌入静态资源");
helper.setText("<html><body><a href=\"http://www.baidu.com\" ></body></html>", true);
javaMailSender.send(mimeMessage);
}
@Test
public void testMimeInlineMail() throws Exception { //发送HTML格式含图片的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("FX_SKY");
helper.setTo("ricky_feng@163.com");
helper.setSubject("主题:嵌入静态资源");
helper.setText("<html><body><img src=\"cid:logo\" ></body></html>", true);
FileSystemResource logoFile = new FileSystemResource(new File("logo.jpg"));
helper.addInline("logo", logoFile);
javaMailSender.send(mimeMessage);
}
@Test
public void testAttachmentMail() throws Exception { //发送含附件的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);// 第二个参数设置为true,表示允许添加附件
helper.setFrom("FX_SKY");
helper.setTo("ricky_feng@163.com");
helper.setSubject("发送含图片附件的邮件");
helper.setText("含有附件的邮件");
helper.addAttachment(MimeUtility.encodeText("附件-1.jpg"), new File("E:/attachment1.jpg"));
helper.addAttachment(MimeUtility.encodeText("附件-2.jpg"), new File("E:/attachment2.jpg"));
javaMailSender.send(mimeMessage);
}
}
模板邮件
通常我们使用邮件发送服务的时候,都会有一些固定的场景,比如重置密码、注册确认等,给每个用户发送的内容可能只有小部分是变化的。所以,很多时候我们会使用模板引擎来为各类邮件设置成模板,这样我们只需要在发送时去替换变化部分的参数即可。
Java中常用的模板引擎有 FreeMarker 和Velocity,下面我们以Velocity为例做演示。
pom.xml 引入velocity 依赖:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
在resources/templates/ 目录下,创建一个模板页面mail.vm:
<html>
<body>
<h3>你好, ${username}, 这是一封模板邮件!</h3>
<h3><a href="${activation_url}">点击激活: ${activation_url}</a></h3>
</body>
</html>
最后,我们在单元测试中加入发送模板邮件的测试用例,代码如下:
@Test
public void testSendTemplateMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("FX_SKY");
helper.setTo("ricky_feng@163.com");
helper.setSubject("主题:模板邮件");
VelocityContext context = new VelocityContext();
context.put("username", "Velocity");
context.put("activation_url", "http://www.baidu.com");
Template template = ve.getTemplate("templates/mail.vm");
StringWriter sw = new StringWriter();
template.merge(context, sw);
String text = sw.toString();
helper.setText(text, true);
mailSender.send(mimeMessage);
}