SpringBoot发送邮件定时任务
一、定时任务启动注解
@SpringBootApplication
@EnableScheduling //定时任务的注解
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
二、pom依赖
<!-- mail邮件服务启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
三、application-mail.properties
#QQ\u90AE\u7BB1\u90AE\u4EF6\u53D1\u9001\u670D\u52A1\u914D\u7F6E
spring.mail.host=smtp.qq.com
spring.mail.port=587
## qq邮箱
spring.mail.username=1311328238@qq.com
## 这里填邮箱的授权码
spring.mail.password=asdasdasdasd
四、工具类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);
}
}
五、测试
@Component
class DemoApplicationTests {
@Autowired
private MailUtils mailUtils;
/**
* 定时邮件发送任务,每月1日中午12点整发送邮件
*/
@Scheduled(cron = "0 0 12 1 * ?")
void sb(){
// 定制邮件内容
StringBuffer content = new StringBuffer();
content.append("HelloWorld");
//分别是接收者邮箱,标题,内容
mailUtils.sendSimpleEmail("123456789@qq.com","自定义标题",content.toString());
}
}
其他
cron表达式格式:
其中 {秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}
详细链接