10-10-定时邮件发送

一、邮件发送工具类实现

创建一个用于邮件发送服务的工具类MailUtils,并编写一个发送简单邮件的方法

@Component
public class MailUtils {

    @Autowired
    private JavaMailSenderImpl mailSender;
    @Value("${spring.mail.username}")
    private String mailfrom;

    // 发送简单邮件
    public void sendSimpleEmail(String mailto, String title, String content) {

        //  定制邮件发送内容
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailfrom);
        message.setTo(mailto);
        message.setSubject(title);
        message.setText(content);

        // 发送邮件
        mailSender.send(message);

    }

}

二、邮件定时发送调度实现

创建com.itheima.myblog.web.task包和一个定时任务管理类ScheduleTask,并编写了定时调度方法sendEmail(),并通过“@Scheduled(cron = ”0 0 12 1 * ?“)”注解指定了在每月1日中午12点调用邮件发送任务发送邮件。

@Component
public class ScheduleTask {

    @Autowired
    private StatisticMapper statisticMapper;

    @Autowired
    private MailUtils mailUtils;

    @Value("${spring.mail.username}")
    private String mailto;



    /**
     * 定时邮件发送任务,每月1日中午12点整发送邮件
     */

    @Scheduled(cron = "0 0 12 1 * ?")
//    @Scheduled(cron = "0 */3 * * * ? ")
    public void sendEmail(){

        //  定制邮件内容
        long totalvisit = statisticMapper.getTotalVisit();
        long totalComment = statisticMapper.getTotalComment();
        StringBuffer content = new StringBuffer();
        content.append("博客系统总访问量为:"+totalvisit+"人次").append("\n");
        content.append("博客系统总评论量为:"+totalComment+"人次").append("\n");
        mailUtils.sendSimpleEmail(mailto,"个人博客系统流量统计情况",content.toString());

    }

}

三、开启基于注解的定时任务

在项目启动类上使用@EnableScheduling注解开启基于注解的定时任务支持

@EnableScheduling
@SpringBootApplication
public class BlogSystemApplication {
    ...
}

四、效果展示

在项目启动成功后,持续关注配置的测试邮箱信息,效果如图

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值