JavaMail
springboot 发送邮件:
-
导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>2.4.1</version> </dependency>
-
配置mail
spring.mail.username=a19917117294@163.com spring.mail.password=xxxxxx spring.mail.protocol=smtp spring.mail.host=smtp.163.com spring.mail.properties.mail.smtp.ssl.enable=true
-
具体实现
@Autowired
JavaMailSenderImpl javaMailSender;
@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("感谢信");
simpleMailMessage.setFrom("发信邮箱");
simpleMailMessage.setTo("收信邮箱");
simpleMailMessage.setText("元旦快乐");
javaMailSender.send(simpleMailMessage);
}
@Test
void contextLoads2() throws MessagingException {
Session session = javaMailSender.getSession();
MimeMessage mimeMessage = new MimeMessage(session);
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.addAttachment("1.jpg",new File("E:\\DownLoad\\壁纸图\\JMM.jpg"));
helper.setText("<p style='color:red'>送你一个女朋友</p>");
helper.setFrom("a19917117294@163.com");
helper.setTo("1191009512@qq.com");
helper.setSubject("女票");
helper.setSentDate(new Date());
javaMailSender.send(mimeMessage);
}
异步任务
@Service
public class MyService {
//异步任务注解
@Async
public void sayHello() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
System.out.println("数据处理中");
}
}
@RestController
public class MyController {
@Autowired
MyService service;
@GetMapping("/hello")
public String hello() throws InterruptedException {
service.sayHello();
return "ok";
}
}
@SpringBootApplication
//开启异步任务注解
@EnableAsync
public class AsyncApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
}
}
定时任务
>TaskScheduler 任务调度
>
>TaskExecutor 任务执行者
>
>@EnableScheduling 开启定时任务注解
>
>@Scheduled 定时任务注解类
//cron表达式: 1/3 31 21 23 * ?
// 秒 分 时 日 月 0-7(周一到周六,0和7表示礼拜天)
//下面表示每月23号21点31分每三秒执行一次,从第一秒开始
@Scheduled(cron = "1/3 31 21 23 * ?")
public void scheduledTask(){
System.out.println("执行ing");
}