邮件任务

  1. 引入pom依赖

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

    spring.mail.username=你的QQ邮箱
    spring.mail.password=你的QQ授权码
    spring.mail.host=smtp.qq.com
    # qq需要配置ssl
    spring.mail.properties.mail.smtp.ssl.enable=true
    

    授权码获取步骤:

    在QQ邮箱中的设置->账户->开启pop3和smtp服务

  3. Spring单元测试

    @SpringBootTest
    class SwaggerDemoApplicationTests {
        @Autowired
        JavaMailSenderImpl mailSender;
    
        @Test
        void contextLoads() {
            //邮件设置1:一个简单的邮件
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("我是主题");
            message.setText("我是正文");
    
            message.setTo("你的邮箱@qq.com");
            message.setFrom("你的邮箱@qq.com");
            mailSender.send(message);
        }
        
         @Test
        public void contextLoads2() throws MessagingException {
            //邮件设置2:一个复杂的邮件
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    
            helper.setSubject("我是主题");
            helper.setText("我是正文");
    
            //发送附件
            helper.addAttachment("1.jpg",new File("D:\\dell\\下载\\a.png"));
    
            helper.setTo("你的邮箱@qq.com");
            helper.setFrom("你的邮箱@qq.com");
            mailSender.send(mimeMessage);
        }
    
    }
    

然后你的邮箱就会收到邮件啦!

posted @ 2020-06-01 18:28  hellowen2020  阅读(194)  评论(0)    收藏  举报