springboot与任务(邮件任务)

  • 邮件发送需要引入spring-boot-starter-mail
  • Spring Boot 自动配置MailSenderAutoConfiguration
  • 定义MailProperties内容,配置在application.yml中
  • 自动装配JavaMailSender
  • 测试邮件发送

 

 

  1. pom文件配置:
        <!--邮件发送-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-mail</artifactId>
            </dependency>

     

  2. applicationproperties配置:
    spring.mail.username=442624769@qq.com
    #自己邮箱的授权码
    spring.mail.password=lufufllqrylobijg
    spring.mail.host=smtp.qq.com
    
    #开启安全(有时需要)
    spring.mail.properties.mail.smtp.ssl.enable=true

     

  3. 测试类:
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class Springboot04TaskApplicationTests {
    
    
        @Autowired
        JavaMailSenderImpl mailSender;
    
        @Test
        public void contextLoads() {
            //创建一个简单的消息邮件
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setSubject("通知-今晚开会");
            simpleMailMessage.setText("今晚7点30开会");
    
            simpleMailMessage.setTo("2163370170@qq.com");
            simpleMailMessage.setFrom("442624769@qq.com");
            mailSender.send(simpleMailMessage);
        }
    
        @Test
        public void test02() throws MessagingException {
            //创建一个复杂的消息邮件
    
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //准备上传文件
            MimeMessageHelper helper =  new MimeMessageHelper(mimeMessage,true);
            //邮件设置
            helper.setSubject("通知-今晚开会");
            //设置写的这段内容为html
            helper.setText("<b style='color:red'>今天7:30开会</b>",true);
    
            helper.setTo("2163370170@qq.com");
            helper.setFrom("442624769@qq.com");
    
            //上传文件
            helper.addAttachment("1.png",new File("C:\\Users\\44262\\Desktop\\1.png"));
    
            mailSender.send(mimeMessage);
    
    
        }
    }

     

posted @ 2019-05-20 16:58  MagicAsa  阅读(162)  评论(0编辑  收藏  举报