目次
以下に示すように https://start.spring.io/ に移動します" > 以下に示すように https://start.spring.io/ に移動します
は https を使用します://www.tianqiapi.com /index 彼らは私にプロモーション料もくれませんでした。ただ、私が長期間使用したことへのご褒美としてでした。" > は https を使用します://www.tianqiapi.com /index 彼らは私にプロモーション料もくれませんでした。ただ、私が長期間使用したことへのご褒美としてでした。
新しい " >新しい
今日有雨,狗子请带伞!
今日天气如下
" >ここでは、 Tencent メールボックスを例に挙げると、まずメール送信用の認証コードを取得します。
コントロール層 " >コントロール層
@EnableSchedulingスケジュールされたタスク" >Statement@EnableSchedulingスケジュールされたタスク
SpringbootEmailApplication " >直接開始SpringbootEmailApplication
ホームページ Java &#&チュートリアル Javaで天気を送る機能を実装(コード付き)

Javaで天気を送る機能を実装(コード付き)

Jun 19, 2020 pm 12:50 PM
java タイミング

Javaで天気を送る機能を実装(コード付き)

Java は天気を送信する機能を実装します (コード付き)

無意識のうちに、また梅雨がやってきました。あなたのパートナーはよく傘を忘れますか? このとき、定期的に傘を持ってくるよう促すメールを自動的に送信するプログラムを作成してください。彼女はあなたを尊敬していますか? はい、もちろん、あなたのターゲットが包囲ライオンなら、私はそれについては言いませんでした ~


Javaで天気を送る機能を実装(コード付き)

#テクノロジースタック
Spring Boot 2.3.1

Jdk 1.8

Maven

インスタンスをすばやく作成する

以下に示すように https://start.spring.io/ に移動します


クリックJavaで天気を送る機能を実装(コード付き)GENERATE
解凍してインポートするための zip を作成しますideaそれは Can

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@NoArgsConstructorpublic 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@NoArgsConstructorpublic class Whours {
    // 14日20时
    private String day;
    //中雨
    private String wea;
    //28℃ 实时温度
    private String tem;
    //无持续风向
    private String win;
    // 风速 3-4级
    private String winSpeed;}
ログイン後にコピー
Weather インターフェイス

は https を使用します://www.tianqiapi.com /index 彼らは私にプロモーション料もくれませんでした。ただ、私が長期間使用したことへのご褒美としてでした。



Javaで天気を送る機能を実装(コード付き)カプセル化された天気 API の簡単なデモンストレーション

Javaで天気を送る機能を実装(コード付き)天気 API の取得とメール送信のロジック

新しい

EmailService.java

インターフェイス<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>package com.github.ekko.springtools.service;import com.github.ekko.springtools.model.Weather;import java.util.List;public interface EmailService { boolean sendSimpleMessage(); List&lt;Weather&gt; getWeather();}</pre><div class="contentsignin">ログイン後にコピー</div></div>実装

EmailService

インターフェイス<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>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;@Servicepublic class EmailServiceImpl implements EmailService { private final static String FROM_MAIL = &quot;你的发送邮箱,和配置文件中相同&quot;; private final static String TO_MAIL = &quot;接收人邮箱&quot;; private final static String APPID = &quot;你申请的天气api的appid,自行替换&quot;; private final static String APPSECRET = &quot;你申请的天气api的APPSECRET,自行替换&quot;; 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(&quot;今日份天气到了~~&quot;); mimeMessageHelper.setText(buildHtml(getWeather().get(0)), true); emailSender.send(message); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public List&lt;Weather&gt; getWeather() { HttpRequest httpRequest = HttpUtil.createGet(&quot;https://www.tianqiapi.com/api?version=v1&amp;&quot; + &quot;appid=&quot; + APPID + &quot;&amp;appsecret=&quot; + APPSECRET + &quot;&amp;cityid=101020100&quot;); String res = httpRequest.execute().body(); Object data = JSON.parseObject(res).get(&quot;data&quot;); return JSON.parseArray(JSON.toJSONString(data), Weather.class); } private String buildHtml(Weather weather) { StringBuffer html = new StringBuffer(&quot;&quot;); html.append(&quot;&lt;!DOCTYPE html&gt;\n&quot; + &quot;&lt;html&gt;\n&quot; + &quot;&lt;head&gt;\n&quot; + &quot;&lt;meta charset=\&quot;utf-8\&quot;&gt;\n&quot; + &quot;&lt;title&gt;文档标题&lt;/title&gt;\n&quot; + &quot;&lt;/head&gt;&lt;body&gt;&quot;); if (weather.getWea().contains(&quot;雨&quot;)) { html.append(&quot;&lt;h1 id=&quot;今日有雨-狗子请带伞&quot;&gt;今日有雨,狗子请带伞!&lt;/h1&gt;&quot;); } html.append(&quot;&lt;hr/&gt;&lt;h3 id=&quot;今日天气如下&quot;&gt;今日天气如下&lt;/h3&gt;&lt;table&gt;&lt;tr&gt;&lt;th&gt;时间&lt;/th&gt;&lt;th&gt;天气&lt;/th&gt;&lt;th&gt;温度&lt;/th&gt;&lt;/tr&gt;&quot;); Optional.ofNullable(weather.getHours()) .orElse(new ArrayList&lt;&gt;()) .forEach(whours -&gt; { html.append(&quot;&lt;tr&gt;&lt;td&gt;&quot;) .append(whours.getDay()) .append(&quot;&lt;/td&gt;&lt;td&gt;&quot;) .append(whours.getWea()) .append(&quot;&lt;/td&gt;&lt;td&gt;&quot;) .append(whours.getTem()) .append(&quot;&lt;/td&gt;&lt;/tr&gt;&quot;); }); html.append(&quot;&lt;/table&gt;&lt;/body&gt;&quot; + &quot;&lt;/html&gt;&quot;); return html.toString(); }}</pre><div class="contentsignin">ログイン後にコピー</div></div> ##コード内の #APPID

APPSECRET
アカウント情報の送信を設定しますJavaで天気を送る機能を実装(コード付き)

ここでは、 Tencent メールボックスを例に挙げると、まずメール送信用の認証コードを取得します。

SMTP
アドレスとそのメールボックスのリンクをクエリすると、Javaで天気を送る機能を実装(コード付き)

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

が表示されます。 Configuration application.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
ログイン後にコピー

コントロール層

Statement@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@EnableSchedulingpublic 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;@SpringBootApplicationpublic class SpringbootEmailApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootEmailApplication.class, args);
	}}
ログイン後にコピー

効果

ちょっと醜いですが、使って自分で美化してください

Javaで天気を送る機能を実装(コード付き)

##読んでいただきありがとうございます。皆さんが多くの恩恵を受けることを願っています。 推奨チュートリアル: 「Java ビデオ チュートリアル

以上がJavaで天気を送る機能を実装(コード付き)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Javaの平方根 Javaの平方根 Aug 30, 2024 pm 04:26 PM

Java の平方根のガイド。ここでは、Java で平方根がどのように機能するかを、例とそのコード実装をそれぞれ示して説明します。

Javaの完全数 Javaの完全数 Aug 30, 2024 pm 04:28 PM

Java における完全数のガイド。ここでは、定義、Java で完全数を確認する方法、コード実装の例について説明します。

Java の乱数ジェネレーター Java の乱数ジェネレーター Aug 30, 2024 pm 04:27 PM

Java の乱数ジェネレーターのガイド。ここでは、Java の関数について例を挙げて説明し、2 つの異なるジェネレーターについて例を挙げて説明します。

ジャワのウェカ ジャワのウェカ Aug 30, 2024 pm 04:28 PM

Java の Weka へのガイド。ここでは、weka java の概要、使い方、プラットフォームの種類、利点について例を交えて説明します。

Javaのアームストロング数 Javaのアームストロング数 Aug 30, 2024 pm 04:26 PM

Java のアームストロング番号に関するガイド。ここでは、Java でのアームストロング数の概要とコードの一部について説明します。

Javaのスミス番号 Javaのスミス番号 Aug 30, 2024 pm 04:28 PM

Java のスミス番号のガイド。ここでは定義、Java でスミス番号を確認する方法について説明します。コード実装の例。

Java Springのインタビューの質問 Java Springのインタビューの質問 Aug 30, 2024 pm 04:29 PM

この記事では、Java Spring の面接で最もよく聞かれる質問とその詳細な回答をまとめました。面接を突破できるように。

Java 8 Stream Foreachから休憩または戻ってきますか? Java 8 Stream Foreachから休憩または戻ってきますか? Feb 07, 2025 pm 12:09 PM

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです

See all articles