美文网首页
Spring boot集成mail发送邮件

Spring boot集成mail发送邮件

作者: 缘木与鱼 | 来源:发表于2019-12-23 17:49 被阅读0次

    需要先添加mail依赖

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

    邮件的配置

    spring:
      mail:
        host: smtp.163.com
        username: xxxxxx@163.com
        password: xxxxxxxxx   # 此密码为授权码
        enable: true
        smtp:
          auth: true
        starttls:
          enable: true
          required: true
    

    启动文件

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class EmailSpringApplication {
        public static void main(String[] args) {
            SpringApplication.run(EmailSpringApplication.class, args);
        }
    }
    

    编写测试类

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = EmailSpringApplication.class)
    public class ApplicationTests {
    
        @Autowired
        private JavaMailSender mailSender;
    
        @Test
        public void sendSimpleEmail() {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            // 从这个邮箱发送
            mailMessage.setFrom("xxxxxx@163.com");
            // 发给下面的邮箱
    //        mailMessage.setTo("xxxxxx@163.com");
    //        mailMessage.setTo("xxxxxx@qq.com");
            // 邮箱的主题
            mailMessage.setSubject("主题: 验证码");
            // 邮箱的内容
            mailMessage.setText("12345678");
            mailSender.send(mailMessage);
        }
    }
    

    运行测试即可发送

    相关文章

      网友评论

          本文标题:Spring boot集成mail发送邮件

          本文链接:https://www.haomeiwen.com/subject/kdctoctx.html