在Spring Boot中使用JavaMailSender发送各类邮件

Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例来练习一下如何在Spring Boot中使用JavaMailSender发送邮件。

快速入门

在Spring Boot的工程中的pom.xml中引入spring-boot-starter-mail依赖:

     
     
1
2
3
4
     
     
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-mail </artifactId>
</dependency>

在完成了依赖引入之后,只需要在application.properties中配置相应的属性内容。

下面我们以QQ邮箱为例,在application.properties中加入如下配置(用户名就是qq邮箱名、密码是POP3/SMTP服务授权码):

     
     
1
2
3
4
5
6
     
     
spring.mail.host=smtp.qq.com
spring.mail.username=用户名
spring.mail.password=密码
spring.mail.properties.mail.smtp.auth= true
spring.mail.properties.mail.smtp.starttls.enable= true
spring.mail.properties.mail.smtp.starttls.required= true


注意:QQ邮箱要开启POP3/SMTP服务

在设置》帐户

          


通过单元测试来实现一封简单邮件的发送:

         由于Spring Boot的starter模块提供了自动化配置,所以在引入了spring-boot-starter-mail依赖之后,会根据配置文件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使用的地方直接@Autowired来引入邮件发送对象。

     
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
     
     
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
@Autowired
private JavaMailSender mailSender;
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom( "xxxx@qq.com");
message.setTo( "xxxx@qq.com");
message.setSubject( "主题:简单邮件");
message.setText( "简单邮件内容");
mailSender.send(message);
}
}

到这里,一个简单的邮件发送就完成了。

进阶使用

在上例中,我们通过使用SimpleMailMessage实现了简单的邮件发送,但是实际使用过程中,我们还可能会带上附件、或是使用邮件模块等。这个时候我们就需要使用MimeMessage来设置复杂一些的邮件内容,下面我们就来依次实现一下。

发送附件

在上面单元测试中加入如下测试用例(通过MimeMessageHelper来发送一封带有附件的邮件):

     
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
     
     
@Test
public void sendAttachmentsMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom( "xxx@qq.com");
helper.setTo( "xxxx@qq.com");
helper.setSubject( "主题:有附件");
helper.setText( "有附件的邮件");
FileSystemResource file1 = new FileSystemResource(new File("C:\\Users\\Administrator\\Desktop\\feiQ.png"));      FileSystemResource file2 = new FileSystemResource(new File("C:\\Users\\Administrator\\Desktop\\Think in Java.pdf"));      helper.addAttachment("附件-1.png", file1);      helper.addAttachment("附件-2.pdf", file2);
mailSender.send(mimeMessage);
}
嵌入静态资源

除了发送附件之外,我们在邮件内容中可能希望通过嵌入图片等静态资源,让邮件获得更好的阅读体验,而不是从附件中查看具体图片,下面的测试用例演示了如何通过MimeMessageHelper实现在邮件正文中嵌入静态资源。

     
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
     
     
@Test
public void sendInlineMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom( "xxxx@qq.com");
helper.setTo( "xxxx@qq.com");
helper.setSubject( "主题:嵌入静态资源");
StringBuffer sb = new StringBuffer();     sb.append("<h1>大标题-h1</h1>").append("<p style='color:#F00'>红色字</p>")   .append("<p style='text-align:right'>右对齐</p>");     helper.setText(sb.toString(), true);    //注意:调用setText时需要在第二个参数传入true,这样才会使用HTML格式发送邮件              //   helper.setText("<html><body><img src=\"cid:feiq\"><p><img src=\"cid:qq\"></body></html>",true); //   FileSystemResource file1 = new FileSystemResource(new File("C:\\Users\\Administrator\\Desktop\\feiQ.png")); //  FileSystemResource file2 = new FileSystemResource(new File("C:\\Users\\Administrator\\Desktop\\qq.png")); //   helper.addInline("feiq", file1); //   helper.addInline("qq", file2);
mailSender.send(mimeMessage);
}

这里需要注意的是addInline函数中资源名称feiq需要与正文中cid:feiq对应起来

模板邮件

通常我们使用邮件发送服务的时候,都会有一些固定的场景,比如重置密码、注册确认等,给每个用户发送的内容可能只有小部分是变化的。所以,很多时候我们会使用模板引擎来为各类邮件设置成模板,这样我们只需要在发送时去替换变化部分的参数即可。

在Spring Boot中使用模板引擎来实现模板化的邮件发送也是非常容易的,下面我们以velocity为例实现一下。

引入velocity模块的依赖:

     
     
1
2
3
4
     
     
<dependency>
<groupId>org.springframework.boot </groupId>
<artifactId>spring-boot-starter-velocity </artifactId>
</dependency>

resources/templates/下,创建一个模板页面template.vm

     
     
1
2
3
4
5
     
     
<html>
<body>
<h3>你好, ${username}, 这是一封模板邮件! </h3>
</body>
</html>

我们之前在Spring Boot中开发Web应用时,提到过在Spring Boot的自动化配置下,模板默认位于resources/templates/目录下

最后,我们在单元测试中加入发送模板邮件的测试用例,具体如下:

     
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
     
     
@Test
public void sendTemplateMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom( "xxxxx@qq.com");
helper.setTo( "xxxxx@qq.com");
helper.setSubject( "主题:模板邮件");
Map<String, Object> model = new HashedMap();
model.put( "username", "lyz");
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "template.vm", "UTF-8", model);
helper.setText(text, true);
mailSender.send(mimeMessage);
}

尝试运行一下,就可以收到内容为你好, lyz, 这是一封模板邮件!的邮件。这里,我们通过传入username的参数,在邮件内容中替换了模板中的${username}变量。


  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值