SpringBoot系列:Springboot实现异步任务、定时任务、邮件任务

  这个小项目还是挺好玩的,把异步、定时、邮件三个任务整理到一起,那就是发送异步的定时邮件!直接来看具体实现把~嘿嘿,代码在文章最后给出!




1、新建项目工程

  之前在Springboot整合mybatis的文章给出了怎么新建工程,需要的小伙伴可以看看工程怎么建立的,其实有些依赖在新建过程中就可以添加了的。
  文章地址~冲呀!Springboot整合mybatis


2、依赖坐标

        <!--        引入thymeleaf      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>

        <!--        引用邮件依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <!--        邮件依赖-->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>jakarta.mail</artifactId>
            <version>1.6.4</version>
            <scope>compile</scope>
        </dependency>

3、写个工具类 记住写自己邮箱地址

public class EmailUtils {

    @Autowired
    JavaMailSenderImpl mailSender;

    public void SendMain(String subject,String text, String setToPerpel) throws MessagingException {
        //邮件设置2:一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setSubject(subject);
        helper.setText(text,true);

        //发送附件
        helper.addAttachment("1.png",new File("src/main/resources/static/img/1.png"));
        helper.addAttachment("2.png",new File("src/main/resources/static/img/2.png"));

        //选择收件人
        helper.setTo(setToPerpel);
        helper.setFrom("你的邮箱地址0@qq.com");

        mailSender.send(mimeMessage);
    }
}

4、打开自己QQ邮箱,在设置->账户中找到

在这里插入图片描述
将pop3/SMTP服务打开,记住授权码


5、编写application.yml配置文件

server:
  port: 80
spring:
  mail:
    username: 你的邮箱地址
    password: 授权码
    host: smtp.qq.com
    #qq需要配置ssl
    properties:
      mail: true
      smtp: true
      ssl: true
      enable: true

6、在Config文件中添加MyConfig类,让Spring接管工具类的自动注入

在这里插入图片描述

@Configuration
public class Myconfig {

    @Bean
    public EmailUtils emailUtils(){
        return new EmailUtils();
    }
}


7、在serive文件中添加AsyncService类,类中添加同步发送邮件、异步发送邮件服务

@Service
public class AsyncService {

    @Autowired
    private EmailUtils emailUtils;

    public void sendSyncEmail(String subject, String text,String setToPerpel) throws MessagingException {
        try {
            Thread.sleep(3000);
        }catch (InterruptedException  e){
            e.printStackTrace();
        }
        System.out.println("同步:邮件正在发送....");
        emailUtils.SendMain(subject,text,setToPerpel);

    }

    /**
     * 声明这是一个异步服务
     */
    @Async
    public void sendAsyncEmail(String subject, String text,String setToPerpel) throws MessagingException{
        try {
            Thread.sleep(3000);
        }catch (InterruptedException  e){
            e.printStackTrace();
        }
        System.out.println("异步:邮件正在发送....");
        emailUtils.SendMain(subject,text,setToPerpel);

    }
}

8、在controller文件中添加EmailFaceController类,控制前端是同步发送还是异步发送,定时邮件任务


@RestController
public class SendEmailController {

    @Autowired
    private AsyncService asyncService;


    /**
     * 发送同步邮件
     */
    @GetMapping("/sendSyncEmail")
    public String sendSyncEmail(@RequestParam("Subject") String subject,
                                @RequestParam("content") String content,
                                @RequestParam("people")  String setToPerpel)
            throws MessagingException {
        try {
            System.out.println(subject);
            System.out.println(content);
            System.out.println(setToPerpel);
            asyncService.sendSyncEmail(subject,content,setToPerpel);
        }catch (MessagingException e){
            return "邮箱地址有误";
        }
        return "发送成功";
    }

    /**
     * 发送异步邮件
     */
    @GetMapping("/sendAsyncEmail")
    public String sendAsyncEmail(
            @RequestParam("ASubject") String subject,
            @RequestParam("Acontent") String content,
            @RequestParam("Apeople") String setToPerpel
            ){
        try {
            System.out.println(subject);
            System.out.println(content);
            System.out.println(setToPerpel);
            asyncService.sendAsyncEmail(subject,content,setToPerpel);
        }catch (MessagingException e){
            return "邮箱地址有误";
        }
        return "发送成功";
    }


    /**
     * 定时发送邮件
     *  //秒   分   时     日   月   周几
     * 定时任务:每天的22点30分30S 发送一封邮件
     */
 
    @Scheduled(cron = "30 30 22 1/1 * ? ")
    public String EmailScheduled(){

        //设置日期格式
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
        String nowTime = sm.format(new Date());
        try {
            asyncService.sendAsyncEmail(
                    "今日邮件",
                    "你好啊",
                    "邮箱地址@qq.com");
        }catch (MessagingException e){
            return "邮箱地址有误";
        }
        return nowTime + "  的定时邮件已经为您发送";
    }
}

9、在controller文件中添加EmailFaceController类,发送邮件页面

@Controller
public class EmailFaceController {

    @RequestMapping("/send")
    public String toSendFace(){
        return "sendEmail";
    }

}

10、在template文件中添加mail的thymeleaf模板文件sendEmail.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Vinda的同步、异步定时邮件发送</title>
</head>
<body>
<div style="text-align: center">
    <div id="sendSync">
        <form method="get" name="Sync"  th:action="@{/sendSyncEmail}">&emsp;题:<input type="text" id="Subject" name="Subject" /><br>&emsp;容:<input type="text" id="content" name="content" /><br>
            收件人:<input type="text" id="people" name="people" /><br>
            <input type="submit" value="发送">
        </form>
    </div>

    <div id="sendAsync">
        <form method="get" name="Async" th:action="@{/sendAsyncEmail}">&emsp;题:<input type="text" id="ASubject" name="ASubject" /><br>&emsp;容:<input type="text" id="Acontent" name="Acontent" /><br>
            收件人:<input type="text" id="Apeople" name="Apeople" /><br>
            <input type="submit" value="发送">
        </form>
    </div>

</div>

</body>
</html>

11、启动程序

在启动类添加如下注解:
@EnableAsync //开启异步注解功能
@EnableScheduling //开启定时功能
在这里插入图片描述
地址栏输入http://localhost:80/send,出现一下页面,上面是同步发送邮件,同步发送邮件,等到邮件发送完毕,才能跳转到成功界面,而使用异步发送邮件,任务会在后台发送,并且跳过等待转到成功界面
在这里插入图片描述


12、同步发送邮件

在这里插入图片描述

在这里插入图片描述


13、异步发送邮件

在这里插入图片描述
在这里插入图片描述


13、打开我自己的邮箱,检测我刚刚给自己发的邮件

因为我在这里填写是自己的邮箱,验证就方便了:
在这里插入图片描述
同步结果:
在这里插入图片描述
异步结果:
在这里插入图片描述

  都是可以使用的,定时任务就是可以自己测,千万不要学了技术就每一秒钟就发送给你的好友,这样做是很有可能被腾讯爸爸注意到的,总结完毕,代码已经上传,可以下载玩玩,不足之处请留言交流,快乐就好~加油!!

-----------------Vinda的GitHub代码-------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值