一、邮件发送工具类实现
创建一个用于邮件发送服务的工具类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 {
...
}
四、效果展示
在项目启动成功后,持续关注配置的测试邮箱信息,效果如图