• 基于springboot实现了后台定时统计数据报表并将数据生成excel文件作为附件,然后通过邮件发送通知的功能


    概述

    本例子基于springboot实现了后台定时统计数据报表并将数据生成excel文件作为附件,然后通过邮件发送通知的功能。

    详细

    一、准备工作

     1、首先注册两个邮箱,一个发送邮箱,一个接收邮箱。

     2、发送邮箱开启IMAP/SMTP/POP3服务,记录得到的授权码

    1.png

    二、项目结构及具体实现

    1、项目结构

    0.png

    2、实现代码

    配置文件:

    1. server:
    2. port: 8088
    3. spring:
    4. mail:
    5. host: smtp.163.com
    6. port:
    7. username: demodashi2021002@163.com
    8. password: WGWRIGYQSCPGBJCC
    9. protocol: smtp
    10. test-connection: true
    11. default-encoding: UTF-8
    12. email:
    13. temp: C:/email/
    14. receiver: demodashi2021001@163.com

    邮件服务接口:实现邮件发送功能。

    1. /**
    2. * 发送带附件的邮件
    3. *
    4. * @param receiver 收件人地址
    5. * @param subject 邮件主题
    6. * @param content 邮件内容
    7. * @param filePath 附件地址
    8. * @param cc 抄送地址
    9. * @throws MessagingException 邮件发送异常
    10. */
    11. @Override
    12. public void sendAttachmentsMail(String receiver, String subject, String content, String filePath, String... cc) throws MessagingException {
    13. MimeMessage message = mailSender.createMimeMessage();
    14. MimeMessageHelper helper = new MimeMessageHelper(message, true);
    15. helper.setFrom(sender);
    16. helper.setTo(receiver);
    17. helper.setSubject(subject);
    18. helper.setText(content, true);
    19. if (ArrayUtil.isNotEmpty(cc)) {
    20. helper.setCc(cc);
    21. }
    22. FileSystemResource file = new FileSystemResource(new File(filePath));
    23. String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
    24. helper.addAttachment(fileName, file);
    25. mailSender.send(message);
    26. }

    定时发送任务:本地测试设置每十秒运行一次定时任务。

    1. @Scheduled(cron = "10/20 * * ? * ?")
    2. private void sendEventEmailTask() {
    3. LOGGER.info("=========启动邮件发送任务=============");
    4. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    5. String startTime = getPastDate(7) + " 00:00:00";
    6. String endTime = sdf.format(new Date()) + " 23:59:59";
    7. String subject = "最近一周的数据";
    8. this.emailJob(startTime, endTime,subject);
    9. LOGGER.info("=========结束邮件发送任务=============");
    10. }

    三、演示效果

    运行项目后等待十秒,查看日志:

    3.png

    查看接收邮箱:

    4.png

    附件:

    5.png

  • 相关阅读:
    nginx
    7zip自带hash校验功能
    混沌工程平台 ChaosBlade-Box 新版重磅发布
    BN的作用原理
    使用VueCli快速搭建项目
    为什么访问同一个网址却返回不同的内容
    在找工作时的准备工作:结合现状,针对意向企业做好充分准备
    Django实现Hello World
    RK3568-mpp(Media Process Platform)媒体处理软件平台
    这份神仙面试笔记,简直把所有Java知识面试题写出来了
  • 原文地址:https://blog.csdn.net/hanjiepo/article/details/132690838