Spring Boot 2.x 能定时给你对象发送天气情况

简介: 不知不觉,又到了雨季,你对象是不是经常忘记带伞呢,这个时候写一个自动定时发送邮件的程序,提醒她带伞,会不会对你崇拜有加呢,当然,如果你对象是一位攻城狮,当我没讲~

前言

不知不觉,又到了雨季,你对象是不是经常忘记带伞呢,这个时候写一个自动定时发送邮件的程序,提醒她带伞,会不会对你崇拜有加呢,当然,如果你对象是一位攻城狮,当我没讲~

技术栈

  • Spring Boot 2.3.1
  • Jdk 1.8
  • Maven

快速创建实例

前往 https://start.spring.io/ 如下所示

点击GENERATE生产一个zip解压导入idea即可

pom.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.github.ekko</groupId>
    <artifactId>springboot-email</artifactId>
    <version>1.0.0</version>
    <name>springboot-email</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.6.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
        <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>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <!--阿里云主仓库,代理了maven central和jcenter仓库-->
        <repository>
            <id>aliyun</id>
            <name>aliyun</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <!--阿里云代理Spring 官方仓库-->
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://maven.aliyun.com/repository/spring</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <!--阿里云代理Spring 插件仓库-->
        <pluginRepository>
            <id>spring-plugin</id>
            <name>spring-plugin</name>
            <url>https://maven.aliyun.com/repository/spring-plugin</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>

新建接收天气api的实体

Weather.java

package com.github.ekko.springtools.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
public class Weather {
    private String day;
    private String date;
    private String week;
    //天气情况
    private String wea;
    private String weaImg;
    private String air;
    private String humidity;
    // 空气质量 优
    private String airLevel;
    // 空气质量描述:空气很好,可以外出活动,呼吸新鲜空气,拥抱大自然
    private String airTips;
    private String tem1;
    private String tem2;
    private String tem;
    private List<Whours> hours;
}

Whours.java

package com.github.ekko.springtools.model;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Whours {
    // 14日20时
    private String day;
    //中雨
    private String wea;
    //28℃ 实时温度
    private String tem;
    //无持续风向
    private String win;
    // 风速 3-4级
    private String winSpeed;
}

天气接口

用的是
https://www.tianqiapi.com/index也没给我推广费,也作为我白嫖它这么久的回报吧

封装的天气api简单演示

在这里插入图片描述

获取天气api与发送邮件的逻辑

新建EmailService.java接口

package com.github.ekko.springtools.service;
import com.github.ekko.springtools.model.Weather;
import java.util.List;
public interface EmailService {
    boolean sendSimpleMessage();
    List<Weather> getWeather();
}

实现EmailService接口

package com.github.ekko.springtools.service.impl;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.github.ekko.springtools.model.Weather;
import com.github.ekko.springtools.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class EmailServiceImpl implements EmailService {
    private final static String FROM_MAIL = "你的发送邮箱,和配置文件中相同";
    private final static String TO_MAIL = "接收人邮箱";
    private final static String APPID = "你申请的天气api的appid,自行替换";
    private final static String APPSECRET = "你申请的天气api的APPSECRET,自行替换";
    public JavaMailSender emailSender;
    @Autowired
    public void setEmailSender(JavaMailSender emailSender) {
        this.emailSender = emailSender;
    }
    @Override
    public boolean sendSimpleMessage() {
        try {
            MimeMessage message = emailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            mimeMessageHelper.setTo(TO_MAIL);
            mimeMessageHelper.setFrom(FROM_MAIL);
            mimeMessageHelper.setSubject("今日份天气到了~~");
            mimeMessageHelper.setText(buildHtml(getWeather().get(0)), true);
            emailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public List<Weather> getWeather() {
        HttpRequest httpRequest = HttpUtil.createGet("https://www.tianqiapi.com/api?version=v1&" + "appid=" + APPID + "&appsecret=" + APPSECRET + "&cityid=101020100");
        String res = httpRequest.execute().body();
        Object data = JSON.parseObject(res).get("data");
        return JSON.parseArray(JSON.toJSONString(data), Weather.class);
    }
    private String buildHtml(Weather weather) {
        StringBuffer html = new StringBuffer("");
        html.append("<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "<meta charset=\"utf-8\">\n" +
                "<title>文档标题</title>\n" +
                "</head><body>");
        if (weather.getWea().contains("雨")) {
            html.append("<h1>今日有雨,狗子请带伞!</h1>");
        }
        html.append("<hr/><h3>今日天气如下</h3><table><tr><th>时间</th><th>天气</th><th>温度</th></tr>");
        Optional.ofNullable(weather.getHours())
                .orElse(new ArrayList<>())
                .forEach(whours -> {
                    html.append("<tr><td>")
                            .append(whours.getDay())
                            .append("</td><td>")
                            .append(whours.getWea())
                            .append("</td><td>")
                            .append(whours.getTem())
                            .append("</td></tr>");
                });
        html.append("</table></body>" +
                "</html>");
        return html.toString();
    }
}

代码中的APPID与APPSECRET

设置发送账号信息

这里以腾讯邮箱为例子 ,先获取发送邮件的授权码

查询其邮箱的SMTP地址 ,链接 ,可以看到

使用SSL的通用配置如下:
接收邮件服务器:pop.qq.com,使用SSL,端口号995
发送邮件服务器:smtp.qq.com,使用SSL,端口号465或587
账户名:您的QQ邮箱账户名(如果您是VIP帐号或Foxmail帐号,账户名需要填写完整的邮件地址)
密码:您的QQ邮箱密码
电子邮件地址:您的QQ邮箱的完整邮件地址

配置appliction.properties

server.port=9090
server.servlet.context-path=/mail
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=你的邮箱地址
spring.mail.password=刚刚获取的授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.starttls.enable=true

控制层

声明 @EnableScheduling定时任务给指定方法设置时间表达式@Scheduled(cron = "0 0 8 * * ? ")

package com.github.ekko.springtools.controller;
import com.github.ekko.springtools.model.Weather;
import com.github.ekko.springtools.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@EnableScheduling
public class MailController {
    private EmailService emailService;
    @Autowired
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }
    @GetMapping("/send")
    @Scheduled(cron = "0 0 23 * * ? ")
    public boolean sendEmail() {
        return emailService.sendSimpleMessage();
    }
    @GetMapping("get-weather")
    public List<Weather> getWeather() {
        return emailService.getWeather();
    }
}

启动类

直接启动
SpringbootEmailApplication即可

package com.github.ekko.springtools;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootEmailApplication {
 public static void main(String[] args) {
  SpringApplication.run(SpringbootEmailApplication.class, args);
 }
}

效果

有点丑/将就点/自行美化

本文就是愿天堂没有BUG给大家分享的内容,大家有收获的话可以分享下,想学习更多的话可以到微信公众号里找我,我等你哦。

相关文章
|
8月前
|
XML Java 测试技术
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
这篇文章介绍了Spring5框架的三个新特性:支持@Nullable注解以明确方法返回、参数和属性值可以为空;引入函数式风格的GenericApplicationContext进行对象注册和管理;以及如何整合JUnit5进行单元测试,同时讨论了JUnit4与JUnit5的整合方法,并提出了关于配置文件加载的疑问。
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
|
4月前
|
存储 Java Spring
【Spring】获取Bean对象需要哪些注解
@Conntroller,@Service,@Repository,@Component,@Configuration,关于Bean对象的五个常用注解
113 12
|
4月前
|
存储 Java 应用服务中间件
【Spring】IoC和DI,控制反转,Bean对象的获取方式
IoC,DI,控制反转容器,Bean的基本常识,类注解@Controller,获取Bean对象的常用三种方式
109 12
|
4月前
|
XML 安全 Java
Spring Boot中使用MapStruct进行对象映射
本文介绍如何在Spring Boot项目中使用MapStruct进行对象映射,探讨其性能高效、类型安全及易于集成等优势,并详细说明添加MapStruct依赖的步骤。
120 0
|
6月前
|
Java 调度 开发者
spring的@Scheduled()有几种定时模式?
【10月更文挑战第12天】spring的@Scheduled()有几种定时模式?
249 1
|
6月前
|
前端开发 Java Spring
【Spring】“请求“ 之传递单个参数、传递多个参数和传递对象
【Spring】“请求“ 之传递单个参数、传递多个参数和传递对象
209 2
|
6月前
|
Java Spring
获取spring工厂中bean对象的两种方式
获取spring工厂中bean对象的两种方式
82 1
|
6月前
|
存储 Java 程序员
SpringIOC和DI的代码实现,Spring如何存取对象?@Controller、@Service、@Repository、@Component、@Configuration、@Bean DI详解
本文详细讲解了Spring框架中IOC容器如何存储和取出Bean对象,包括五大类注解(@Controller、@Service、@Repository、@Component、@Configuration)和方法注解@Bean的用法,以及DI(依赖注入)的三种注入方式:属性注入、构造方法注入和Setter注入,并分析了它们的优缺点。
112 0
SpringIOC和DI的代码实现,Spring如何存取对象?@Controller、@Service、@Repository、@Component、@Configuration、@Bean DI详解
|
9月前
|
缓存 安全 Java
Spring高手之路21——深入剖析Spring AOP代理对象的创建
本文详细介绍了Spring AOP代理对象的创建过程,分为三个核心步骤:判断是否增强、匹配增强器和创建代理对象。通过源码分析和时序图展示,深入剖析了Spring AOP的工作原理,帮助读者全面理解Spring AOP代理对象的生成机制及其实现细节。
148 0
Spring高手之路21——深入剖析Spring AOP代理对象的创建
|
8月前
|
安全 Java C#
Spring创建的单例对象,存在线程安全问题吗?
Spring框架提供了多种Bean作用域,包括单例(Singleton)、原型(Prototype)、请求(Request)、会话(Session)、全局会话(GlobalSession)等。单例是默认作用域,保证每个Spring容器中只有一个Bean实例;原型作用域则每次请求都会创建一个新的Bean实例;请求和会话作用域分别与HTTP请求和会话绑定,在Web应用中有效。 单例Bean在多线程环境中可能面临线程安全问题,Spring容器虽然确保Bean的创建过程是线程安全的,但Bean的使用安全性需开发者自行保证。保持Bean无状态是最简单的线程安全策略;
111 0