Springboot 用quartz定时发送邮件
—————项目目录结构——————
———————项目配置————————
1、 添加pom依赖
<!-- mail start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、application.yml配置文件
spring:
mail:
password: **********
default-encoding: UTF-8
host: smtp.qq.com
properties:
mail:
smtp:
starttls:
enable: true
required: true
auth: true
username: *****@qq.com
3、qq邮箱授权码
3.1 登录qq邮箱后进去主页,点击设置
3.2 找到邮箱设置,点击账户
3.3 找到POP3/SMTP服务 点击开启,发送短信就可以获得授权码
4、 在conf包下新增JobFactory.class
package com.hiQiBlog.conf;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
@Component
public class JobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
5、在config包中新增QuartzConfiguration.class
package com.hiQiBlog.config;
import com.hiQiBlog.conf.JobFactory;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration
public class QuartzConfiguration {
@Configuration
@EnableScheduling
public class QuartzConfigration {
@Autowired
private JobFactory jobFactory;
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setOverwriteExistingJobs(true);
schedulerFactoryBean.setJobFactory(jobFactory);
return schedulerFactoryBean;
}
@Bean(name = "scheduler")
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}
}
6、新建SendEmailJob.class
package com.hiQiBlog.job;
import com.hiQiBlog.service.SendEmailSevice;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SendEmailJob implements Job {
@Autowired
private SendEmailSevice emailService;
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
Date date = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("现在的时间是:" + sf.format(date));
System.out.println("开始任务");
emailService.sendEmail();
}
}
7、新建接口层ISendEmailSevice和实现类SendEmailSeviceImpl
package com.hiQiBlog.service;
import com.hiQiBlog.entity.User;
import java.util.List;
public interface ISendEmailSevice {
public boolean sendEmail();
public boolean sendAttachmentMail();
}
package com.hiQiBlog.service.impl;
import com.hiQiBlog.service.ISendEmailSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Service
public class SendEmailSeviceImpl implements ISendEmailSevice {
@Value("${spring.mail.username}")
private String fromEmail;
@Autowired
private JavaMailSender javaMailSender;
@Override
public boolean sendEmail() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo("*******@qq.com");
simpleMailMessage.setFrom(fromEmail);
simpleMailMessage.setSubject("测试");
simpleMailMessage.setText("utf-8");
try {
javaMailSender.send(simpleMailMessage);
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean sendAttachmentMail() {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo("1579258595@qq.com");
helper.setSubject("测试");
helper.setText("utf-8");
helper.setFrom(fromEmail);
try {
javaMailSender.send(mimeMessage);
} catch (Exception e) {
return false;
}
return true;
} catch (MessagingException e) {
e.printStackTrace();
return true;
}
}
}
8、新建接口层IQuartzService和实现类QuartzServiceImpl
package com.hiQiBlog.service;
public interface IQuartzService {
void startJob(String time, String jobName, String group);
void pauseJob(String triggerName, String triggerGroupName);
void resumeJob(String triggerName, String triggerGroupName);
void deleteJob(String triggerName, String triggerGroupName);
void doJob(String triggerName, String triggerGroupName);
void startAllJob();
void shutdown();
}
package com.hiQiBlog.service.impl;
import com.hiQiBlog.job.SendEmailJob;
import com.hiQiBlog.service.IQuartzService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class QuartzServiceImpl implements IQuartzService {
@Autowired
private Scheduler scheduler;
@Override
public void startJob(String time, String jobName, String group) {
try {
JobDetail jobDetail = JobBuilder.newJob(SendEmailJob.class).withIdentity(jobName, group).build();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, group).withSchedule(scheduleBuilder).build();
System.out.println(scheduler.getSchedulerName());
scheduler.scheduleJob(jobDetail, cronTrigger);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void pauseJob(String triggerName, String triggerGroupName) {
try {
JobKey jobKey = new JobKey(triggerName, triggerGroupName);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return;
}
System.out.println("开始暂停一个定时器");
scheduler.pauseJob(jobKey);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
@Override
public void resumeJob(String triggerName, String triggerGroupName) {
try {
JobKey jobKey = new JobKey(triggerName, triggerGroupName);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return;
}
scheduler.resumeJob(jobKey);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
@Override
public void deleteJob(String triggerName, String triggerGroupName) {
try {
JobKey jobKey = new JobKey(triggerName, triggerGroupName);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return;
}
scheduler.deleteJob(jobKey);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
@Override
public void doJob(String triggerName, String triggerGroupName) {
try {
JobKey jobKey = JobKey.jobKey(triggerName, triggerGroupName);
scheduler.triggerJob(jobKey);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
@Override
public void startAllJob() {
try {
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
@Override
public void shutdown() {
try {
scheduler.shutdown();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
8、测试类
package com.hiQiBlog;
import com.hiQiBlog.service.IQuartzService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
IQuartzService e;
@Test
public void testEmail() throws Exception {
e.startJob("*/5 * * * * ? ","zz","zz");
}
}