SpringBoot——异步、定时、发送邮件

一、异步任务

在异步执行的函数上使用注解@Async,并在主配置类上启用(@EnableAsync)

@Service
public class AsyncService {

    @Async
    @Scheduled(cron = "")  //定时任务
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("异步:hello!");
    }
}
@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "hello world!";
    }
}
@EnableAsync  //启用异步任务
@EnableScheduling  //启用定时任务
@SpringBootApplication
public class Springboot20200603Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot20200603Application.class, args);
    }

}

二、定时任务

在需要定时执行的函数上添加注解@Scheduled(cron = “”)
cron是定时表达式:
@Scheduled(cron=“0 */5 * * * ?”) //每5分钟执行一次
@Scheduled(cron=“0 */1 * * * ?”) //每1分钟执行一次

三、发送邮件

1.在pom文件中添加依赖
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
2.配置邮件服务器
spring.mail.username=ning0539@foxmail.com  <!--发送邮件的邮箱地址 -->
spring.mail.password=qtfohyuziiszbiic  <!--邮箱授权码--> 
spring.mail.host=smtp.qq.com <!--通过POP3收取邮件时,发件服务器-->
3.使用JavaMailSenderImpl操作邮件发送
class Springboot20200603ApplicationTests {

    @Autowired
    JavaMailSenderImpl javaMailSender;

    /**
     * 发送简单邮件
     */
    @Test
    void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("测试邮箱服务器");//邮件主题
        message.setText("测试邮件。");//邮件内容
        message.setTo("wang526132456@163.com");//收件人邮箱地址
        message.setFrom("ning0539@foxmail.com");//发件人邮箱地址

        javaMailSender.send(message);
    }


    /**
     * 发送复杂邮件:附件
     */
    @Test
    void sendMail() throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        helper.setSubject("测试邮箱服务器");
        helper.setText("<b style='color:red'>测试复杂邮件。</b>",true);//参数true:是否为html内容
        helper.setTo("wang526132456@163.com");
        helper.setFrom("ning0539@foxmail.com");

        helper.addAttachment("1.jpg",new File("C:\\Users\\K\\Pictures\\1.jpg"));//附件
        helper.addAttachment("2.jpg",new File("C:\\Users\\K\\Pictures\\2.jpg"));

        javaMailSender.send(mimeMessage);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值