SpringBoot配置Email发送功能

前言:在做软工实践项目时,有Email发送验证码验证的需求,因此来简单地学一下如何在SpringBoot中配置Email发送功能。

相信使用过Spring的众多开发者都知道Spring提供了非常好用的 JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用 JavaMailSender 发送邮件。

快速入门

一、准备工作

  • 需要开启POP3、SMTP邮件服务
  • 需要设置客户端授权码
  • 以网易邮箱举例如下:

二、发送模板邮件

1、添加依赖

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

<dependency>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>  

2、绑定配置

application.yml

spring:
    mail:
        host: smtp.163.com
        username: xxxxxx@163.com
        password: xxxxxxxxxxxxxx
        properties:
            mail:
                smtp:
                    starttls:
                        enable: true
                        required: true
注意:在spring.mail.password处的值是需要在邮箱设置里面生成的授权码,这个不是真实的密码。

3、测试发送

@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("dyc87112@qq.com");
        message.setTo("dyc87112@qq.com");
        message.setSubject("主题:简单邮件");
        message.setText("测试邮件内容");

        mailSender.send(message);
    }

}

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

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

注:转载参考自SpringBoot发送注册激活邮件(附HTML模板)SpringBoot配置Email发送功能

posted @ 2020-06-04 19:31  _Spike  阅读(236)  评论(0)    收藏  举报