本文通过SpringBoot整合Email和Quartz来实现定时发送邮件的功能;最终效果是每天上午10:30向某人发送一封邮件。
首先,导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- quartz依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
配置文件
spring:
mail:
host: smtp.qq.com
username: [email protected] #邮箱
password: ************* #授权码
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
业务逻辑层代码:
package com.example.sercive;
public interface SendEmailService {
String sendEmail();
}
实现类:
package com.example.sercive.impl;
import com.example.sercive.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
/**
* @author zhang_hong
* @version 1.0
* @date 2020/1/22 10:12
*/
@Service
public class SendEmailServiceImpl implements SendEmailService {
@Autowired
private JavaMailSender jms;
@Value("${spring.mail.username}")
private String from;
@Override
public String sendEmail() {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
// 接收地址
message.setTo("[email protected]");
// 标题
message.setSubject("一封测试邮件");
// 内容
message.setText("这是一封使用Spring Boot发送的邮件,今晚去洗脚,有空吗!!!");
jms.send(message);
System.out.println("执行了...");
return "发送成功";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
任务类:
package com.example.job;
import com.example.sercive.SendEmailService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
public class SendEmailJob implements Job {
/**
* 注入业务逻辑层对象
*/
@Autowired
private SendEmailService emailService;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//执行任务
emailService.sendEmail();
}
}
配置类:
package com.example.config;
import com.example.job.SendEmailJob;
import org.quartz.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.example"})
public class QuartzConfiguration {
// 使用jobDetail包装job
@Bean
public JobDetail myCronJobDetail() {
return JobBuilder.newJob(SendEmailJob.class).withIdentity("SendEmailJob").storeDurably().build();
}
// 把jobDetail注册到Cron表达式的trigger上去
@Bean
public Trigger CronJobTrigger() {
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 30 10 * * ? *");
return TriggerBuilder.newTrigger()
.forJob(myCronJobDetail())
.withIdentity("myCronJobTrigger")
.withSchedule(cronScheduleBuilder)
.build();
}
}