SpringBoot implements sending love words to objects every day

SpringBoot implements regular sending of rainbow fart mail

I heard that girls like things that are romantic and have a sense of ritual. As a programmer with both talent and beauty, how can I express my love with style but not identity? This article provides you with a practical article , so that you can get rid of the shackles of single dogs.

The program can be packaged as a jar package and published to your own server, and you can send emails to your custom mailbox on time every day. You can also set a timed task on your computer and send it on time.

Realization requirements: send QQ emails to designated mailboxes regularly, update email content in real time (the rainbow fart in each email content is different), customize beautiful templates

Use HttpClient to remotely obtain the content website in the rainbow fart generator website:

  • https://chp.shadiao.app/

  • java Mail implements sending mail

  • SpringBoot integrates Scheduled to send emails regularly

Picture above: QQ mail style (with js dynamic sliding effect)
insert image description here

0. QQ mailbox setting

Before writing the configuration, you need to log in to your mailbox in the browser and set the POP3/SMTP service in account security.
insert image description here

1. Import dependencies

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <!--spring-context-support 则是为将第三方库整合进 Spring 应用上下文 提供支持-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <!-- httpclient 依赖 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>

yml configuration file


spring:
  mail:
    username: [email protected]  # 自己邮箱地址
    password: xxxxxxx        # SMTP|POP3|IMAP协议授权码
    host: smtp.qq.com        # 服务器地址。参考邮箱服务运营商提供的信息。
    properties:
      mail:
        smtp:
          auth: true          # 开启smtp协议验证
    port: 587      

# 发给谁的邮箱
she:
  mail: [email protected]

2. Remote crawling of rainbow farts

https://chp.shadiao.app/api.php
mainly uses network requests to obtain response data HttpClients

/**远程获取要发送的信息*/
    public static String getOneS(){
    
    
        try {
    
    
            //创建客户端对象
            HttpClient client = HttpClients.createDefault();
            /*创建地址 https://du.shadiao.app/api.php*/
            HttpGet get = new HttpGet("https://chp.shadiao.app/api.php");
            //发起请求,接收响应对象
            HttpResponse response = client.execute(get);
            //获取响应体,响应数据是一种基于HTTP协议标准字符串的对象
            //响应体和响应头,都是封装HTTP协议数据。直接使用可能出现乱码或解析错误
            HttpEntity entity = response.getEntity();
            //通过HTTP实体工具类,转换响应体数据
            String responseString = EntityUtils.toString(entity, "utf-8");
       	    return responseString;
        } catch (IOException e) {
    
    
            throw  new RuntimeException("网站获取句子失败");
        }
    }

3. Mail sending

Mail sending is dependently integrated by springboot, and the specific implementation details are encapsulated. We only need to pay attention to the business code itself, mainly injecting the JavaMailSender object

1. Create information sending object
2. Create complex mail sending assistant object
3. Set mail sender, receiver, subject content, mail content
4. Send mail

  public void sendMessage(String subject,String message) {
    
    
        try {
    
    
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);//发送者邮件邮箱
            helper.setTo(sheMail);//收邮件者邮箱
            helper.setSubject(subject);//发件主题
            helper.setText(message,true);//发件内容
            mailSender.send(helper.getMimeMessage());//发送邮件
        } catch (MessagingException e) {
    
    
            e.printStackTrace();
        }
    }

4. Send scheduled tasks

It is not necessary to add @Controller @RequestMapping("/sendMessage"), and the main purpose of adding it is to enable the access path to send emails, but it is not necessary.

Realize the scheduled task annotation @Scheduled(cron = "0 20 5,17 * * *") mainly adopts the cron expression format: six or seven placeholders respectively represent: {seconds} {minutes} {hours} {date } {month} {week} {year (can be empty)}
Note: To enable the scheduled task @EnableScheduling on the bootstrap class

@Controller
//@Component
public class MyScheduled {
    
    

    @Autowired
    private SendMessage sendMessage;

// cronExpression定义时间规则:秒 分钟 小时 日期 月份 星期 年(可选)
    /*定时执行任务方法 每天5点和17点20执行该任务*/
//    @Scheduled(cron = "0 20 5,17 * * *")
    @Scheduled(cron = "0/30 * * * * ?")
//    @RequestMapping("/sendMessage")
    public String dsrw() {
    
    
        //获取彩虹屁
        String message = sendMessage.getOneS();
        //获取邮件模板
        String content = getContent(message);
        //发送邮件
        sendMessage.sendMessage("❤宝贝", content);
        return "index.html";
    }

    public String getContent(String message) {
    
    
        //格式化日期
        String date = new SimpleDateFormat("yyyy年MM月dd日").format(new Date());

        //自定义样式邮件模板
        String content = "此处放置你自己的能够以的邮件模板页面并开启html解析,true";
        return content;
    }
}

Details of placeholders in cron expressions:

Explanation of each placeholder in the cron expression:
{seconds}{minutes} ==> allowable value range: 0~59, empty values ​​are not allowed, if the value is illegal, the scheduler will throw a SchedulerException "*" represents
every Trigger every 1 second;
"," means triggering at the specified number of seconds, such as "0,15,45" means triggering the task at 0 seconds, 15 seconds and 45 seconds
"-" means triggering within the specified range, such as" 25-45" means triggering from the start of 25 seconds to the end of 45 seconds, triggering once every 1 second
"/" means the trigger step (step), the value before "/" means the initial value (""equal to" 0" ), the following value represents the offset, such as "0/20" or "/20" means starting from 0 seconds and triggering once every 20 seconds, that is, triggering once in 0 seconds and once in 20 seconds, Trigger once in 40 seconds; "5/20" means trigger once in 5 seconds, trigger once in 25 seconds, trigger once in 45 seconds; "10-45/20" means hit within [10,45] within 20 seconds Time point trigger, that is, trigger once every 10 seconds, once every 30 seconds
{hour} ==> allowable value range: 0~23, null value is not allowed, if the value is illegal, the scheduler will throw a SchedulerException, The placeholder is the same as the number of seconds
{date} ==> allowed value range: 1~31, empty value is not allowed, if the value is illegal, the scheduler will throw a SchedulerException
{week} ==> allowed value range: 1~7 (SUN-SAT), 1 represents Sunday (the first day of the week), and so on, 7 represents Saturday (the last day of the week), null values ​​are not allowed, if the value is illegal, the scheduler will Throw SchedulerException
{year} ==> allowable value range: 1970~2099, allow to be empty, if the value is illegal, the scheduler will throw SchedulerException
Note: Except {date} and {week} can use "?" to achieve mutual exclusion and express meaningless information, other placeholders must have specific time meanings, and the dependency relationship is: year->month- >Date (week)->hour->minute->seconds
3. The powerful charm of cron expressions lies in the flexible horizontal and vertical combinations and simple syntax. With cron expressions, you can write almost any time you want to trigger Point and period
Classic case:
"30 * * * * ?" triggers the task every half minute
"30 10 * * * ?" triggers the task at 10 minutes and 30 seconds per hour
"30 10 1 * * ?" every day at 1:10:30 Second trigger task "30 10 1 20 * ?" Trigger task "30 10 1 20 10 ? *" at
1:10:30 on the 20th of each month Trigger task "30 10 1 20 10 ? 2011" Trigger task "30 10 1 ? 10 * 2011" at 1:10:30 on October 20, 2011 Trigger task "30 10 1 ? 10 SUN 2011" at 1:10:30 every day in October 2011 2011 Trigger the task "15,30,45 * * * * ?" at 1:10:30 every Sunday in October, every 15 seconds, 30 seconds, and 45 seconds, trigger the task "15-45 * * * * ?" 15 to Within 45 seconds, the task "15/5 * * * * ?" will be triggered every second. Every 15 seconds of each minute, the task "15-30/5 * * * * ?" will be triggered every 5 seconds. Start triggering between seconds and 30 seconds, and trigger every 5 seconds








"0 0/3 * * * ?" Starts at 0 minutes and 0 seconds of every hour, and triggers every three minutes
"0 15 10 ? * MON-FRI" Triggers the task at 10:15:0 ​​seconds from Monday to Friday
"0 15 10 L * ?” Trigger the task
“0 15 10 LW * ?” at 10:15:00 on the last day of each month “0 15 10 LW * ?” Trigger the task
“0 15 10 ? * at 10:15:00 on the last working day of each month 5L" triggers the task at 10:15:00 on the last Thursday of every month
"0 15 10 ? * 5#3" triggers the task at 10:15:00 on the third Thursday of every month

5. Custom Template

Provide a private collection of beautiful html templates

<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <base target="_blank"/>
    <style id="scrollbar" type="text/css">::-webkit-scrollbar {
    
    
        width: 0 !important
    }

    pre {
    
    
        white-space: pre-wrap !important;
        word-wrap: break-word !important;
        *white-space: normal !important
    }

    #letter img {
    
    
        max-width: 300px
    }</style>
    <style id="from-wrapstyle" type="text/css">#form-wrap {
    
    
        overflow: hidden;
        height: 447px;
        position: relative;
        top: 0px;
        transition: all 1s ease-in-out .3s;
        z-index: 0
    }</style>
    <style id="from-wraphoverstyle" type="text/css">#form-wrap:hover {
    
    
        height: 1300px;
        top: -200px
    }</style>
</head>
<body>
<div style="width: 530px;margin: 20px auto 0;height: 1000px;">
    <div id="form-wrap"><img src="https://cdn.jsdelivr.net/gh/Akilarlxh/[email protected]/source/img/before.png"
                             alt="before"
                             style="position: absolute;bottom: 126px;left: 0px;background-repeat: no-repeat;width: 530px;height: 317px;z-index:-100">
        <div style="position: relative;overflow: visible;height: 1500px;width: 500px;margin: 0px auto;transition: all 1s ease-in-out .3s;padding-top:200px;">
            <form>
                <div style="background: white;width: 95%;max-width: 800px;margin: auto auto;border-radius: 5px;border: 1px solid;overflow: hidden;-webkit-box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.12);box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.18);">
                    <img style="width:100%;overflow: hidden;"
                         src="https://ae01.alicdn.com/kf/U5bb04af32be544c4b41206d9a42fcacfd.jpg"/>
                    <div style="padding: 5px 20px;"><br>
                        <div><h3
                                style="text-decoration: none; color: rgb(17,17,17); text-align: center;font-family: 华文新魏">
                            来自<span style="color: #fa7a0a">清峰</span>的留言:</h3>
                        </div>

                        <br>
                        <!--内容区域height:200px-->
                        <div id="letter"
                             style="overflow:auto;height:285px;width:100%;display:block;word-break: break-all;word-wrap: break-word;">
                            <div style="text-align: center; border-bottom: #ddd 1px solid;border-left: #ddd 1px solid;padding-bottom: 20px;background-color: #eee;margin: 15px 0px;padding-left: 20px;padding-right: 20px;border-top: #ddd 1px solid;border-right: #ddd 1px solid;padding-top: 20px;font-family: "
                                 Arial
                            ", "Microsoft YaHei" , "黑体" , "宋体" , sans-serif;">
                            <!--要显示的内容-->
                            <span style="color: #fc9b0a;font-family: 华文新魏">
                                我浑浑噩噩走过二十年, 做过天上仙, 受过万人谴, 以为甘甜苦楚全都尝过遍。 只有你回首一眼, 才知这是人间。</span>

                        </div>

                        <div style="text-align: center;margin-top: 40px;"><img
                                src="https://ae01.alicdn.com/kf/U0968ee80fd5c4f05a02bdda9709b041eE.png" alt="hr"
                                style="width:100%; margin:5px auto 5px auto; display: block;"/><a
                                style="text-transform: uppercase;text-decoration: none;font-size: 17px;border: 2px solid #6c7575;color: #2f3333;padding: 10px;display: inline-block;margin: 10px auto 0;background-color: rgb(246, 214, 175);"
                                target="_blank" href="#">2020年5月20号</a>
                        </div>
                        <p style="font-size: 12px;text-align: center;color: #999;">你若盛开,清峰自来!<br><a
                                style="text-decoration:none; color:rgb(30,171,234)" href="http://www.qingfenginn.top">@
                            清峰小栈</a>
                        </p>

                    </div>

                </div>
        </div>
        </form>
    </div>
    <img src="https://cdn.jsdelivr.net/gh/Akilarlxh/[email protected]/source/img/after.png" alt="after"
         style="      position: absolute;bottom: -2px;left: 0;background-repeat: no-repeat;width: 530px;height: 259px;z-index:100">
</div>
</div>
</body>

</body>
</html>

6. Set timed tasks

The program can be packaged as a jar package and published to your own server, and you can send emails to your custom mailbox on time every day. You can also set a timed task on your computer and send it on time.
1. For how to deploy to the server, please refer to https://blog.csdn.net/weixin_45019350/article/details/108963951
2. Windows computer setting timed task
win10 timed transport jar package to create a task in the task scheduler
insert image description here

insert image description here
1) Create a new trigger
insert image description here
2) Create a new operation, enter the executed jar command in the program or script, click OK
insert image description here
3) Then you can see the created task
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45019350/article/details/112856975