Java實作發送天氣功能(附程式碼)
不知不覺,又到了雨季,你對像是不是經常忘記帶傘呢,這個時候寫一個自動定時發送郵件的程序,提醒她帶傘,會不會對你崇拜有加呢,當然,如果你物件是一位攻城獅,當我沒講~
技術棧
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@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;}
#天氣介面
用的是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;@Servicepublic 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 id="今日有雨-狗子请带伞">今日有雨,狗子请带伞!</h1>"); } html.append("<hr/><h3 id="今日天气如下">今日天气如下</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@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實作發送天氣功能(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java代碼可以在不同操作系統上無需修改即可運行,這是因為Java的“一次編寫,到處運行”哲學,由Java虛擬機(JVM)實現。 JVM作為編譯後的Java字節碼與操作系統之間的中介,將字節碼翻譯成特定機器指令,確保程序在任何安裝了JVM的平台上都能獨立運行。

Java程序的編譯和執行通過字節碼和JVM實現平台獨立性。 1)編寫Java源碼並編譯成字節碼。 2)使用JVM在任何平台上執行字節碼,確保代碼的跨平台運行。

Java性能与硬件架构密切相关,理解这种关系可以显著提升编程能力。1)JVM通过JIT编译将Java字节码转换为机器指令,受CPU架构影响。2)内存管理和垃圾回收受RAM和内存总线速度影响。3)缓存和分支预测优化Java代码执行。4)多线程和并行处理在多核系统上提升性能。

使用原生庫會破壞Java的平台獨立性,因為這些庫需要為每個操作系統單獨編譯。 1)原生庫通過JNI與Java交互,提供Java無法直接實現的功能。 2)使用原生庫增加了項目複雜性,需要為不同平台管理庫文件。 3)雖然原生庫能提高性能,但應謹慎使用並進行跨平台測試。

JVM通過JavaNativeInterface(JNI)和Java標準庫處理操作系統API差異:1.JNI允許Java代碼調用本地代碼,直接與操作系統API交互。 2.Java標準庫提供統一API,內部映射到不同操作系統API,確保代碼跨平台運行。

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

禪工作室 13.0.1
強大的PHP整合開發環境

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3漢化版
中文版,非常好用

Atom編輯器mac版下載
最受歡迎的的開源編輯器