关于最近很火的给对象的公众号之java spring boot 定时发送邮件教学
最近给女朋友的接口测试号很流行,但是需要商家或者企业资质,但是我们可以通过邮箱实现相同的功能。大致效果如下(源代码底部):
话不多说,直接上教程,首先新建spring boot项目,这个过程不复杂我就不过多阐述了,直接上页面图,画框部分是我们需要关注的代码片段,其他的属于无关代码。如果自己重新创建项目可以只创建这几个类。
新建两个实体类,其中一些注解不用管,原本是想从数据库中拿但只是教学就没必要了。
天气查询的方法,这里使用的是第三方接口,聚合数据,进入官网搜索天气预报api,找到就行了。点击申请是免费的,一天拥有30次权限,申请过后在个人中心里面找到天气预报api,然后有一串key,自己更换下就好。
package com.example.sendemail.util;import com.example.sendemail.entity.weatherEntity;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;@Component
public class SimpleWeather {// 天气情况查询接口地址public static String API_URL = "http://apis.juhe.cn/simpleWeather/query";// 接口请求Keypublic static String API_KEY = "你自己的key";public static weatherEntity weather =new weatherEntity();/*** 根据城市名查询天气情况** @param cityName*/public weatherEntity queryWeather(String cityName) {Map<String, Object> params = new HashMap<>();//组合参数params.put("city", cityName);params.put("key", API_KEY);String queryParams = urlencode(params);String response = doGet(API_URL, queryParams);try {JSONObject jsonObject = JSONObject.fromObject(response);int error_code = jsonObject.getInt("error_code");if (error_code == 0) {JSONObject result = jsonObject.getJSONObject("result");JSONObject realtime = result.getJSONObject("realtime");System.out.printf("城市:%s%n", result.getString("city"));System.out.printf("天气:%s%n", realtime.getString("info"));System.out.printf("温度:%s%n", realtime.getString("temperature"));System.out.printf("湿度:%s%n", realtime.getString("humidity"));System.out.printf("风向:%s%n", realtime.getString("direct"));System.out.printf("风力:%s%n", realtime.getString("power"));System.out.printf("空气质量:%s%n", realtime.getString("aqi"));weather.setCity(result.getString("city"));weather.setInfo(realtime.getString("info"));weather.setTemperature(realtime.getString("temperature"));weather.setHumidity(realtime.getString("humidity"));weather.setDirect(realtime.getString("direct")+realtime.getString("power"));weather.setAqi(realtime.getString("aqi"));weather.setPower(realtime.getString("power"));return weather;} else {weather.setCity("重庆");weather.setInfo("查询失败");weather.setTemperature("查询失败");weather.setHumidity("查询失败");weather.setDirect("查询失败");weather.setAqi("查询失败");weather.setPower("查询失败");System.out.println("调用接口失败:" + jsonObject.getString("reason"));return weather;}} catch (Exception e) {e.printStackTrace();}return null;}/*** get方式的http请求** @param httpUrl 请求地址* @return 返回结果*/public static String doGet(String httpUrl, String queryParams) {HttpURLConnection connection = null;InputStream inputStream = null;BufferedReader bufferedReader = null;String result = null;// 返回结果字符串try {// 创建远程url连接对象URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString());// 通过远程url连接对象打开一个连接,强转成httpURLConnection类connection = (HttpURLConnection) url.openConnection();// 设置连接方式:getconnection.setRequestMethod("GET");// 设置连接主机服务器的超时时间:15000毫秒connection.setConnectTimeout(5000);// 设置读取远程返回的数据时间:60000毫秒connection.setReadTimeout(6000);// 发送请求connection.connect();// 通过connection连接,获取输入流if (connection.getResponseCode() == 200) {inputStream = connection.getInputStream();// 封装输入流,并指定字符集bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));// 存放数据StringBuilder sbf = new StringBuilder();String temp;while ((temp = bufferedReader.readLine()) != null) {sbf.append(temp);sbf.append(System.getProperty("line.separator"));}result = sbf.toString();}} catch (IOException e) {e.printStackTrace();} finally {// 关闭资源if (null != bufferedReader) {try {bufferedReader.close();} catch (IOException e) {e.printStackTrace();}}if (null != inputStream) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (connection != null) {connection.disconnect();// 关闭远程连接}}return result;}/*** 将map型转为请求参数型** @param data* @return*/public static String urlencode(Map<String, ?> data) {StringBuilder sb = new StringBuilder();for (Map.Entry<String, ?> i : data.entrySet()) {try {sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");} catch (UnsupportedEncodingException e) {e.printStackTrace();}}String result = sb.toString();result = result.substring(0, result.lastIndexOf("&"));return result;}
}
发送邮件使用的是spring boot已经封装好的工具‘
package com.example.sendemail.util;import com.example.sendemail.entity.EmailEntity;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;import javax.annotation.Resource;@Component
public class MailUtil {@Resourceprivate JavaMailSender javaMailSender;@Resourceprivate MailProperties mailProperties;public void sendMail(EmailEntity email){SimpleMailMessage message = new SimpleMailMessage();message.setTo(email.getEmailAddress());message.setFrom(mailProperties.getUsername());message.setSubject(email.getSubject());message.setText(email.getWeather().toString()+email.getText());javaMailSender.send(message);}
}
然后就是发送邮件的类,这里我写了两个,一个是调用接口区发送,也就是地址栏输入地址,还有个是定时任务,可根据自己的需求,定时发送,这里天气是实时获取的。
package com.example.sendemail.scheduled;import com.example.sendemail.entity.EmailEntity;
import com.example.sendemail.entity.weatherEntity;
import com.example.sendemail.service.EmailService;
import com.example.sendemail.util.MailUtil;
import com.example.sendemail.util.SimpleWeather;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.text.SimpleDateFormat;
import java.util.Date;@Configuration
@EnableScheduling
@RequestMapping("/test")
public class scheduledController {@Resourceprivate MailUtil mailUtil;@Resourceprivate SimpleWeather simpleWeather;@Autowiredprivate EmailService service;@RequestMapping("/test")@ResponseBodypublic String start() throws MessagingException {//地址城市String city = "重庆";weatherEntity weather = simpleWeather.queryWeather(city);EmailEntity email = new EmailEntity();//收件人email.setEmailAddress("xxxxx@qq.com");//标题email.setSubject("dear");//正文email.setText("\n元气满满");email.setWeather(weather);mailUtil.sendMail(email);return "发送成功";}//定时任务(周一至周五) 秒 分 时 日 月 星期@Scheduled ( cron = "0 21 14 1-31 1-12 1-5 ")public void start2() throws MessagingException {//地址城市String city = "重庆";weatherEntity weather = simpleWeather.queryWeather(city);EmailEntity email = new EmailEntity();//收件人email.setEmailAddress("xxxxxx@qq.com");//标题email.setSubject("dear");//设置天气email.setWeather(weather);//正文(天气后的内容)email.setText("\n元气满满");mailUtil.sendMail(email);}}
然后是配置文件yml
server:port: 8080 spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/email?useUnicode=true&characterEncoding=utf-8username: rootpassword: 123456 # 邮箱配置mail:host: smtp.163.comusername: yaojiayi0720@163.compassword: ACUIDKYDKXEXIAJJ
最后是依赖,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.7.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>SendEmail</artifactId><version>0.0.1-SNAPSHOT</version><name>SendEmail</name><description>SendEmail</description><properties><java.version>18</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency> <!-- 邮箱依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.2</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.8.0</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.8.0</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.8.5</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.2.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.75</version></dependency><dependency><groupId>net.oschina.zcx7878</groupId><artifactId>fastdfs-client-java</artifactId><version>1.27.0.0</version></dependency><dependency><groupId>com.github.tobato</groupId><artifactId>fastdfs-client</artifactId><version>1.26.4</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.5</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>
代码链接:https://gitee.com/yao-jiayi/SendEmail.git
下载这个就行,直接上传的rar包
关于最近很火的给对象的公众号之java spring boot 定时发送邮件教学相关推荐
- 新增对象时生成uuid传递到数据库_技术译文 | UUID 很火但性能不佳?今天我们细聊一聊...
作者:Yves Trudeau Yves 是 Percona 的首席架构师,专门研究分布式技术,例如 MySQL Cluster,Pacemaker 和 XtraDB cluster.他以前是 MyS ...
- python有什么好玩的库_你知道Python很火!那你知道它有哪些好玩的库吗?
原标题:你知道Python很火!那你知道它有哪些好玩的库吗? 本文来源:sun菜菜(今日头条作者) 原文链接:https://www.toutiao.com/a6498615748884169230/ ...
- mybatis代码自动生成器_最近很火的文章自动生成器,python源码公开了(内附python代码)
学了python,但是又不知道可以用来干嘛.开发一个计算器?太low了.开发一个网站?感觉网站涉及太多知识点,一个人搞不定.不用慌,本文介绍一个最近很火的一个文章自动生成器,它是用python写的,能 ...
- 手机联系人头像包_一组抖音上很火的表情包,这里都有,一起来可可爱爱吧
我是最新抖音表情包 马上到表情包轿车带火花|马上到表情包白色汽车动图 em..不知道为什么这个表情包也很火,感jio没什么特别, 这个就厉害了,你以为我是雨伞?那你就错了. 砰~可可爱爱!太萌了. 像 ...
- matplotlib-bilibili,抖音很火的动态数据视频自动生成(第四节)-视频,语音合成
" matplotlib-bilibili,抖音很火的动态数据视频自动生成(第四节)-视频,语音自动合成" 还记得上一节中我们所提到的数据动态视频吗?这次,为了让大家更加方便的制 ...
- python小说自动生成器_最近很火的文章自动生成器,python源码公开了(内附python代码)...
学了python,但是又不知道可以用来干嘛.开发一个计算器?太low了.开发一个网站?感觉网站涉及太多知识点,一个人搞不定.不用慌,本文介绍一个最近很火的一个文章自动生成器,它是用python写的,能 ...
- 10分钟用Python爬取最近很火的复联4影评
10分钟用Python爬取最近很火的复联4影评 欲直接下载代码文件,关注我们的公众号哦!查看历史消息即可! <复仇者联盟4:终局之战>已经上映快三个星期了,全球票房破24亿美元,国内票房破 ...
- python人工智能算法很难_为什么AI很火,但是落地很难?
人工智能(AI)技术在产业当代化的海潮下向各个平台分泌,包含市政.交通.医疗.商用等,跟着5G商用的东风,现在AI技术更火了,不过朋友们能够都有发掘,AI固然很火,但真确落地很难,这是为何呢? 会导致 ...
- python找工作难吗-Python虽然很火,为啥找工作这么难?
原标题:Python虽然很火,为啥找工作这么难? 前几天看到某论坛有人提了这么个问题,Python这么火,为啥找工作这么难呢? 这两年因为第三波人工智能热潮让 Python火了一把,让中小学生.非程序 ...
最新文章
- Loader 知识梳理(2) initLoader和restartLoader的区别
- STM32f407---oled屏幕配套取字模软件使用
- hyperledger fabric v2.4 默认区块大小 配置文件位置
- SpringBoot入门篇-HelloWorld案例
- 【计算理论】计算理论总结 ( 上下文无关文法 | 乔姆斯基范式 | 乔姆斯基范式转化步骤 | 示例 ) ★★
- Unity 无法识别视频
- R语言实战——单个总体均值的区间估计
- 51单片机LED 8*8点阵屏显示图形
- # 汉洛塔问题的解决思路及其代码
- android实现日历
- Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available
- 一名合格的IT项目经理 这八项核心技能不能缺
- 如果你已经厌倦了情人节的玫瑰
- 被封了?教你如何解封chatgpt账号,中英版都有
- Rimworld Mod制作教程12 集群AI机制介绍
- 《尚硅谷大数据Hadoop》教程
- oracle Day1
- c语言程序 存款利息的计算,【c语言】存款利息的计算
- 乐橙育儿机器人 众筹_乐橙智能生活发布育儿机器人“小乐”
- 深度学习的员工离职预测
热门文章
- openwrt开机自启动
- 007. 如何培养自己的赚钱能力
- [转]mailto用法
- 图片使用css3滤镜改变图片颜色
- SAP 零售行业 在企业后台为财务记账的业务方案
- 计算机的快捷键以及Dos命令
- python怎么安装本地的egg_怎么安装python中egg包
- 全国计算机大赛简报,《2019年(第12届)中国大学生计算机设计大赛》简报
- Proxmox ve(PVE)中安装openwrt
- 微软正式发布Visual Studio 2013 Update 3 (2013.3) RTM