hduwbf

需求

最近因为业务的变更,需要对老用户进行发送邮件处理。目前市面上也有很多代发邮件的接口,可以接入。由于量不是特别大,放弃了这个途径。改用我们自己通过 smtp 发送邮件来处理。

技术选择

Java 有原生的javax.mail 可以使用,但是比较复杂。基于我们现在项目中使用了Spring Boot,而且 Spring 提供了非常好用的 JavaMailSender 接口实现邮件发送。在Spring Boot的 Starter 模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用 JavaMailSender 发送邮件。

快速入门

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

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

如其他自动化配置模块一样,在完成了依赖引入之后,只需要在application.properties中配置相应的属性内容。下面我们以QQ邮箱为例,在application.properties中加入如下配置(注意替换自己的用户名和密码):

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

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

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

 

到这里,一个简单的邮件发送就完成了,运行一下该单元测试,看看效果如何?

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

进阶使用

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

发送附件

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

 1 @Test
 2 public void sendAttachmentsMail() throws Exception {
 3 
 4     MimeMessage mimeMessage = mailSender.createMimeMessage();
 5 
 6     MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
 7     helper.setFrom("xxxxx@qq.com");
 8     helper.setTo("xxxxx@qq.com");
 9     helper.setSubject("主题:有附件");
10     helper.setText("有附件的邮件");
11 
12     FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
13     helper.addAttachment("附件-1.jpg", file);
14     helper.addAttachment("附件-2.jpg", file);
15 
16     mailSender.send(mimeMessage);
17 
18 }

以上就是 Spring Boot 实现发送邮件的方法啦。

相关文章: