springboot定时器 + Javamail + 心知天气API (通过邮件每天给女朋友发送一句情话+当日天气信息+当日生活指数)

①首先登陆邮箱查看授权码,登陆163邮箱到首页点击设置(QQ邮箱也是一样),开启服务,然后新增授权密码(这个得到的密码千万保存好,后面会用到) 

②创建springboot项目,导入关键jar包(如下)后面如果缺少什么包,我每段代码都会放上导入了哪些包可以作为参考 

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.0</version>
        </dependency>

③创建实体对象,邮件业务方法 

import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;

/**
 * @Author YMG
 * @Date 2021/6/22 13:54
 * @Description :
 */
@Data
public class MailDto implements Serializable {

    /**
     * 接受邮箱账户
     */
    @NotEmpty(message = "邮箱不可为空")
    private String[] mail;

    /**
     * 邮箱标题
     */
    @NotEmpty(message = "邮箱标题不可为空")
    private String title;

    /**
     * 要发送的内容
     */
    @NotEmpty(message = "内容不可为空")
    private String content;

}

import com.zh.wit.sendMail.dto.MailDto;

/**
 * @Author YMG
 * @Date 2021/6/22 13:55
 * @Description :
 */
public interface MailService {
    /**
     * 发送邮件
     * @param mailDto d
     */
    void send(MailDto mailDto);

}

import com.zh.wit.sendMail.dto.MailDto;
import com.zh.wit.sendMail.service.MailService;
import lombok.RequiredArgsConstructor;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Author YMG
 * @Date 2021/6/22 13:57
 * @Description :
 */
@Service
@RequiredArgsConstructor
@Component
public class MailServiceImpl implements MailService {

    private final MailSender mailSender;


    @Override
    public void send(MailDto mailDto) {
        // new 一个简单邮件消息对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 和配置文件中的的username相同,相当于发送方(配置文件在下properties)
        message.setFrom("ymg@163.com");
        // 收件人邮箱
        message.setBcc(mailDto.getMail());
        //抄送人(是否给自己邮箱发送)
        message.setCc("ymg@163.com");
        message.setSubject(mailDto.getTitle());
        // 正文
        message.setText(mailDto.getContent());
        // 发送
        mailSender.send(message);

    }
}

④配置application.properties

server.port=9029
#邮件配置
#邮箱服务器地址,如果是QQ邮箱--->(smtp.qq.com)
spring.mail.host=smtp.163.com
#发送邮件的邮箱(自己邮箱)
spring.mail.username=ymg@163.com
#第一步页面配置得到的授权密码
spring.mail.password=EXIPENWAJYHERYDX
spring.mail.default-encoding=UTF-8
#(注意!!!以上配置,本地默认25端口访问邮箱服务器,如果需要放到服务器上,必须添加如下配置,用465端口访问才能访问到邮箱服务器)
#登录服务器是否需要认证
spring.mail.properties.mail.smtp.auth=true
#SSL证书Socket工厂
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
#使用SMTPS协议465端口
spring.mail.properties.mail.smtp.socketFactory.port=465

 ⑤编写定时器执行的方法,不要问为什么写controller,因为前期好测试,使用定时器的话,主程序启动千万别忘了配置

@EnableScheduling注解(启动项目加载定时器)
import com.zh.wit.bo.CommonResult;
import com.zh.wit.bo.RestResult;
import com.zh.wit.sendMail.dto.MailDto;
import com.zh.wit.sendMail.service.MailService;
import com.zh.wit.utils.Per;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;

/**
 * @Author YMG
 * @Date 2021/6/22 13:59
 * @Description :
 */
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/mail")
public class MailController {

    private final MailService mailService;

    //spring定时器注解(每天凌晨三点三分发送邮件),因为凌晨三点三分眼前都还是你
    @Scheduled(cron = "0 03 03 ? * *")
    public void sendMail() throws IOException {
        //收件人数组(可以添加多个邮箱)
        String[] str = {"xxx@qq.com","xxx@163.com"};
        MailDto mailDto = new MailDto();
        mailDto.setMail(str);
        //设置邮件title
        mailDto.setTitle("今天你也要开心!");
        //以下是发送的内容
        mailDto.setContent(Per.getWe());
        mailService.send(mailDto);
    }

}

⑥处理邮件发送的内容,心知天气心知天气 - 高精度气象数据 - 天气数据API接口 - 行业气象解决方案数据解析(这个数据解析写的比较乱,可自行处理一下) 

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author YMG
 * @Date 2021/6/24 14:55
 * @Description : 以下每个URL地址都是(心知天气的API) 只需要更换 城市 还有 购买的key就能访问到数据
 */
public class Per {

    public static String getWe() throws IOException {
        URL url = new URL("https://api.seniverse.com/v3/weather/daily.json?key=SIJ_kXNjjhOcycKI6&location=成都&language=zh-Hans&unit=c&start=0&days=1");
        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                connectionData.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String data = sb.toString();
        JSONObject jsonData = JSON.parseObject(data);
        JSONArray results = jsonData.getJSONArray("results");
        JSONArray daily = results.getJSONObject(0).getJSONArray("daily");
        JSONObject jsonObject = daily.getJSONObject(0);
        Map<String, Object> dailyMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            dailyMap.put(entry.getKey(), entry.getValue());
        }

        return getOneS() + "\n" + "\n" + getYe()
                + "\n" + "===================="
                + "\n" + "白天天气:" + "\t" + dailyMap.get("text_day")
                + "\n" + "晚间天气:" + "\t" + dailyMap.get("text_night")
                + "\n" + "最高温度(℃):" + "\t" + dailyMap.get("high")
                + "\n" + "最低温度(℃):" + "\t" + dailyMap.get("low")
                + "\n" + "相对湿度(%):" + "\t" + dailyMap.get("humidity")
                + "\n" + "当前能见度(km):" + "\t" + getSk().get("visibility")
                + "\n" + "气压(Pa):" + "\t" + getSk().get("pressure")
                + "\n" + "风向:" + "\t" + dailyMap.get("wind_direction")
                + "\n" + "风速(km/h):" + "\t" + dailyMap.get("wind_speed")
                + "\n" + "风力等级:" + "\t" + dailyMap.get("wind_scale")
                + "\n" + "===================="
                + "\n" + "\n" + getSe();
    }


    public static String getSe() throws IOException {
        URL url = new URL("https://api.seniverse.com/v3/life/suggestion.json?key=SIJ_kXNjjhOcycKI6&location=成都&language=zh-Hans");
        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                connectionData.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String data = sb.toString();
        JSONObject jsonData = JSON.parseObject(data);
        JSONArray results = jsonData.getJSONArray("results");

        JSONObject now = results.getJSONObject(0).getJSONObject("suggestion");

        Map<String, Object> suMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : now.entrySet()) {
            suMap.put(entry.getKey(), entry.getValue());
        }
        Map<String, Object> resultMap = new HashMap<>();
        for (String s : suMap.keySet()) {
            JSONObject jsonObject = JSON.parseObject(suMap.get(s).toString());
            String resultStr = jsonObject.getString("brief") + "," + jsonObject.getString("details");
            resultMap.put(s, resultStr);
        }

        return "生活指数:"
                + "\n" + "================================="
                + "\n" + "(空气污染):>>>" + "\t" + resultMap.get("air_pollution")
                + "\n" + "(紫外线):>>>" + "\t" + resultMap.get("uv")
                + "\n" + "(舒适度):>>>" + "\t" + resultMap.get("comfort")
                + "\n" + "(雨伞):>>>" + "\t" + resultMap.get("umbrella")
                + "\n" + "(化妆):>>>" + "\t" + resultMap.get("makeup")
                + "\n" + "(防晒):>>>" + "\t" + resultMap.get("sunscreen")
                + "\n" + "(过敏):>>>" + "\t" + resultMap.get("allergy")
                + "\n" + "(风寒):>>>" + "\t" + resultMap.get("chill")
                + "\n" + "(感冒):>>>" + "\t" + resultMap.get("flu")
                + "\n" + "(约会):>>>" + "\t" + resultMap.get("dating")
                + "\n" + "(运动):>>>" + "\t" + resultMap.get("sport")
                + "\n" + "(旅游):>>>" + "\t" + resultMap.get("travel")
                + "\n" + "(晾晒):>>>" + "\t" + resultMap.get("airing")
                + "\n" + "=================================";
    }


    public static Map<String, Object> getSk() throws IOException {
        URL url = new URL("https://api.seniverse.com/v3/weather/now.json?key=SIJ_kXNjjhOcycKI6&location=成都&language=zh-Hans&unit=c");
        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                connectionData.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String data = sb.toString();
        JSONObject jsonData = JSON.parseObject(data);
        JSONArray results = jsonData.getJSONArray("results");
        JSONObject now = results.getJSONObject(0).getJSONObject("now");
        Map<String, Object> skMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : now.entrySet()) {
            skMap.put(entry.getKey(), entry.getValue());
        }
        return skMap;
    }

    //得到农历生肖
    public static String getYe() throws IOException {
        URL url = new URL("https://api.seniverse.com/v3/life/chinese_calendar.json?key=SIJ_kXNjjhOcycKI6&start=0&days=1");
        URLConnection connectionData = url.openConnection();
        connectionData.setConnectTimeout(1000);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                connectionData.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String data = sb.toString();
        JSONObject jsonData = JSON.parseObject(data);
        JSONObject jsonObject = jsonData.getJSONObject("results");
        JSONArray jsonArray = jsonObject.getJSONArray("chinese_calendar");
        JSONObject chinese_calendar = jsonArray.getJSONObject(0);
        Map<String, Object> chMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : chinese_calendar.entrySet()) {
            chMap.put(entry.getKey(), entry.getValue());
        }
        return chMap.get("date") + "\t" + getWeekOfDate(new Date()) + "\t" + chMap.get("ganzhi_year") + "(" + chMap.get("zodiac") + ")" + "年" + chMap.get("lunar_month_name") + chMap.get("lunar_day_name") + "\t" + chMap.get("lunar_festival")
                + "\t" + chMap.get("solar_term");

    }

    //得到情话
    public static String getOneS() throws IOException {
        //创建客户端对象
        HttpClient client = HttpClients.createDefault();
        /*创建地址 https://api.shadiao.pro/chp*/
        HttpGet get = new HttpGet("https://api.shadiao.pro/chp");
        //发起请求,接收响应对象
        HttpResponse response = client.execute(get);
        //获取响应体,响应数据是一种基于HTTP协议标准字符串的对象
        //响应体和响应头,都是封装HTTP协议数据。直接使用可能出现乱码或解析错误
        HttpEntity entity = response.getEntity();
        //通过HTTP实体工具类,转换响应体数据
        String entityString = EntityUtils.toString(entity, "utf-8");
        String substring = entityString.substring(8);
        String resultSubstring = substring.substring(0, substring.length() - 2);
        Map<String, Object> map = JSON.parseObject(resultSubstring, new TypeReference<Map<String, Object>>() {
        });
        return map.get("text").toString();
    }

    public static String getWeekOfDate(Date date) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    public static void main(String[] args) throws IOException {
        System.out.println(getWe());
    }

}

 ⑦心知天气说明(免费版只能获取基础数据,开发者版才能使用具体功能(以上代码是开发者版编写)首次可以申请获得14天试用版的使用(与开发版功能完全一样,能使用接口全部功能))

 ⑧最终移动端呈现效果如下

⑨最终PC端呈现效果如下

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值