Spring Boot 2.x: 定时给对象发送天气

使用Java写一个定时给对象发送天气的功能

    • 前言
    • 技术栈
    • 快速创建实例
    • pom.xml 文件
    • 新建接收天气api的实体
    • 天气接口
    • 封装的天气api简单演示
    • 获取天气api与发送邮件的逻辑
    • 设置发送账号信息
    • 配置appliction.properties
    • 控制层
    • 启动类
    • 效果
    • 源码地址

Spring Boot 2.x: 定时给对象发送天气_第1张图片

前言

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

技术栈

  • Spring Boot 2.3.1
  • Jdk 1.8
  • Maven

快速创建实例

前往 https://start.spring.io/ 如下所示
Spring Boot 2.x: 定时给对象发送天气_第2张图片
点击GENERATE生产一个zip解压导入idea即可

pom.xml 文件


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.1.RELEASEversion>
        <relativePath/>
    parent>
    <groupId>com.github.ekkogroupId>
    <artifactId>springboot-emailartifactId>
    <version>1.0.0version>
    <name>springboot-emailname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-mailartifactId>
        dependency>
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>4.6.1version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.70version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.12version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
    <repositories>
        
        <repository>
            <id>aliyunid>
            <name>aliyunname>
            <url>https://maven.aliyun.com/repository/publicurl>
            <releases>
                <enabled>trueenabled>
            releases>
            <snapshots>
                <enabled>falseenabled>
            snapshots>
        repository>
        
        <repository>
            <id>spring-milestonesid>
            <name>Spring Milestonesname>
            <url>https://maven.aliyun.com/repository/springurl>
            <releases>
                <enabled>trueenabled>
            releases>
            <snapshots>
                <enabled>falseenabled>
            snapshots>
        repository>
    repositories>
    <pluginRepositories>
        
        <pluginRepository>
            <id>spring-pluginid>
            <name>spring-pluginname>
            <url>https://maven.aliyun.com/repository/spring-pluginurl>
            <releases>
                <enabled>trueenabled>
            releases>
            <snapshots>
                <enabled>falseenabled>
            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
也没给我推广费,也作为我白嫖它这么久的回报吧
Spring Boot 2.x: 定时给对象发送天气_第3张图片

封装的天气api简单演示

Spring Boot 2.x: 定时给对象发送天气_第4张图片

获取天气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("\n" +
                "\n" +
                "\n" +
                "\n" +
                "文档标题\n" +
                "");
        if (weather.getWea().contains("雨")) {
            html.append("

今日有雨,狗子请带伞!

"
); } html.append("

今日天气如下

"); Optional.ofNullable(weather.getHours()).orElse(newArrayList<>()).forEach(whours ->{ html.append("");}); html.append("
时间天气温度
") .append(whours.getDay()) .append("") .append(whours.getWea()) .append("") .append(whours.getTem()) .append("
"
+ ""); return html.toString(); } }

代码中的APPIDAPPSECRET
Spring Boot 2.x: 定时给对象发送天气_第5张图片

设置发送账号信息

这里以腾讯邮箱为例子 ,先获取发送邮件的授权码
Spring Boot 2.x: 定时给对象发送天气_第6张图片
查询其邮箱的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);
	}

}

效果

Spring Boot 2.x: 定时给对象发送天气_第7张图片
有点丑,将就用,自行美化

源码地址

https://github.com/Gleans/SpringBootLearn/tree/master/springboot-email

你可能感兴趣的:(Java,Spring,Boot2.x)