异步任务,邮件发送

异步任务

1、在启动类添加@EnableAsync ,表示 开启异步注解功能

2、在方法上添加@Async,表示异步方法

1
2
3
4
5
6
7
8
9
10
11
12
13
@Service
public class AsyncService {
// 使用注解表示异步任务
@Async
public void hello(){
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理......");
}
}

3、在Controller中直接调用即可

邮件发送

1、导入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2、打开邮箱的POP3/SMTP服务获取授权码,设置->账户->开启pop3和smtp服务

3、编写配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@RestController
public class EmailController {
@Autowired
private JavaMailSenderImpl mailSender;

@RequestMapping("/sendMail")
public String sendMail(){
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject("通知");
mailMessage.setText("hello");
mailMessage.setTo("2824199842@qq.com");
mailMessage.setFrom("2824199842@qq.com");
mailSender.send(mailMessage);
return "send ok";
}

@RequestMapping("/sendMail2")
public String sendMail2() throws Exception{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("通知");
helper.setText("<p style='color:red'>hello~</p>",true);
helper.addAttachment("1.jpg",new File("C:\\Users\\28241\\Pictures\\Saved Pictures\\1.jpg"));// 附件
helper.setTo("2824199842@qq.com");
helper.setFrom("2824199842@qq.com");
mailSender.send(mimeMessage);
return "send ok";
}
}