• SpringBoot使用定时任务发送邮件


    一、导入jar包

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

    二、在application.properties种添加邮箱配置

    QQ邮箱需要设置开启smtp服务,具体的请查询一下如何开启,此处省略

    spring.mail.host=smtp.qq.com
    spring.mail.username=54281****@qq.com
    spring.mail.password=tneawbzduhvf****
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.starttls.required=true

    三、发送邮件类

    package com.example.demo.timedtask;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Component
    public class Scheduler2Task {
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        @Autowired
        private JavaMailSender mailSender;
    
        /*
         * @Scheduled(fixedRate = 6000) 上一次开始执行时间点之后6秒再执行
         * @Scheduled(fixedDelay = 6000) 上一次执行完毕时间之后6秒再执行
         * @Scheduled(initialDelay=1000, fixedRate=6000) 第一次延迟1秒后执行,之后按fixedRate的规则执行
         * */
        @Scheduled(fixedRate = 6000)/*每隔六秒钟执行一次*/
        public void reportCurrentTime() {
            System.out.println("现在时间:" + dateFormat.format(new Date()));
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("542813934@qq.com");
            message.setTo("542813934@qq.com");
            message.setSubject("主题:简单邮件1");
            message.setText("测试邮件内容1");
            mailSender.send(message);
        }
    }
  • 相关阅读:
    秘密花园—那段岁月
    测试那些事儿—软测必备的Linux知识(三)
    测试那些事儿—软测必备的Linux知识(二)
    SharePoint 2010以其他用户身份登录的弹出代码
    JavaScript中cookie的路径(path)和域(domain)
    JavaScript变量不同类型之间的自动、手动类型转换
    编程习惯
    JavaScript的算术、赋值、关系运算符的讲解
    JavaScript的变量命名规则和关键字的介绍
    如何编写及运行JS
  • 原文地址:https://www.cnblogs.com/zhanzhuang/p/10244203.html
Copyright © 2020-2023  润新知