spring-boot-starter-mail 邮件服务
spring-boot-starter-thymeleaf 模板
spring-boot-starter-web Web服务
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.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xiaobai</groupId>
<artifactId>scheduled</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>暖心问候</name>
<description>每天邮件伺候</description>
<properties>
<java.version>1.8</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-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
邮件发送模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>LOVE</title>
</head>
<body>
<!--
更多语法参考 thymeleaf官网
-->
<div class="emailpaged" style="background: #fff;">
<div class="emailcontent" style="width:100%;max-width:720px;text-align: left;margin: 0 auto;padding-top: 20px;padding-bottom: 80px">
<div class="emailtitle" style="border-radius: 5px;border:1px solid #eee;overflow: hidden;">
<h1 style="color:#fff;background: #3798e8;line-height:70px;font-size:24px;font-weight:normal;padding-left:40px;margin:0" th:text="'亲爱的'+${username}+',你好呀!'">
</h1>
<div class="emailtext" style="background:#fff;padding:20px 32px 40px;">
<p style="color: #6e6e6e;font-size:13px;line-height:24px;" th:text="'只想对你说:'"></p>
<br />
<p style="color: #6e6e6e;font-size:13px;line-height:24px;padding:10px 20px;background:#f8f8f8;margin:0" th:text="${content}"></p>
<br/>
<p style="color: #6e6e6e;font-size:13px;line-height:24px;" th:text="'当前时间:'+ ${date}"></p>
<br/>
<p style="color: #6e6e6e;font-size:13px;line-height:24px;" th:text="'温馨提示:'+ ${tishi}"></p>
</div>
<p style="color: #6e6e6e;font-size:13px;line-height:24px;text-align:right;padding:0 32px">邮件来自:
<a href="http://xxx.ducker.xyz" style="color:#51a0e3;text-decoration:none" th:text="'每天爱你的'+${user}"></a>
</p>
</div>
</div>
</div>
</body>
</html>
网站主页代表运行状态
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[[${title}]]</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:400,700|Londrina+Outline|Londrina+Solid" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/normalize.css" />
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link rel="stylesheet" type="text/css" href="css/swing.css" />
<script>document.documentElement.className="js";var supportsCssVars=function(){var e,t=document.createElement("style");return t.innerHTML="root: { --tmp-var: bold; }",document.head.appendChild(t),e=!!(window.CSS&&window.CSS.supports&&window.CSS.supports("font-weight","var(--tmp-var)")),t.parentNode.removeChild(t),e};supportsCssVars()||alert("你的浏览器不支持CSS变量,请使用其它浏览器观看demo。");</script>
</head>
<!--
更多语法参考 thymeleaf官网
-->
<body class="demo-swing">
<main>
<section class="content content--layout">
<h2 class="word word--swing">[[${content}]]</h2>
</section>
</main>
<script src="js/charming.min.js"></script>
<script src="js/anime.min.js"></script>
<script src="js/demo.js"></script>
<script src="js/demo4.js"></script>
</body>
</html>
配置文件
server.port=1111
spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=xxxxxx@qq.com
spring.mail.password=ypfgshtojttriaag
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
# 后缀
spring.thymeleaf.prefix=classpath:/templates/
# 模板格式
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.suffix=.html
# 开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
后台
定时器
package com.xiaobai.scheduled;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ResourceUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
@Configuration
@EnableScheduling
public class SaticScheduleTask {
@Autowired
JavaMailSender javaMailSender;
@Autowired
TemplateEngine templateEngine;
//每天5点20分
@Scheduled(cron = "0 20 5 * * ?")
//三十秒
// @Scheduled(fixedRate=30000)
private void configureTasks() throws MessagingException, IOException {
sendHtml();
}
/**
* @Author xiaodingfeng
* @Description 邮件发送
* @Date 13:10 2021/3/6
* @Param []
* @return void
**/
public void sendHtml() throws MessagingException, IOException{
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setSubject("xxxxxxx");//标题
helper.setFrom("xxxxxx@qq.com","xxxx");//邮箱和昵称
helper.setTo("xxxxxx@qq.com");
Date date = new Date();
Calendar calendar = Calendar.getInstance();
boolean isFirstSunday = (calendar.getFirstDayOfWeek() == Calendar.SUNDAY);
int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
if(isFirstSunday){
weekDay = weekDay - 1;
if(weekDay == 0){
weekDay = 7;
}
}
helper.setSentDate(date);
Context context = new Context();
context.setVariable("username", "xxxx");//对方称谓
context.setVariable("user", "xxxx");//我方称谓
context.setVariable("date",calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+
"月"+calendar.get(Calendar.DATE)+"日"+
calendar.get(Calendar.HOUR_OF_DAY)+"时"+
calendar.get(Calendar.MINUTE)+"分");
context.setVariable("tishi", weekDay>=1&&weekDay<=5?"今天是上课工作时间哦,一天的学习工作要开始了哦!":
"今天是周末哦,经过一个星期的学习工作也要适当休息哦!");
context.setVariable("content", getContent("今天又是爱你的一天!"));
String process = templateEngine.process("template", context);
helper.setText(process,true);
javaMailSender.send(mimeMessage);
}
/**
* @Author xiaodingfeng
* @Description 获取服务器上文本第一行句子,删除该句子,保证不重复,当不存在句子时,返回默认句子
* @Date 12:57 2021/3/6
* @Param []
* @return java.lang.String
**/
public String getContent(String temp) throws IOException {
String str = null;
ArrayList<String> list = new ArrayList<>();
File file = ResourceUtils.getFile("/home/beautiful/love.txt");
// File file = ResourceUtils.getFile("C:\\Users\\XiaoBai\\Desktop\\love.txt"); //绝对路径
// ClassPathResource classPathResource = new ClassPathResource("love.txt"); //当前项目下
InputStream is = new FileInputStream(file);
// InputStream is = classPathResource.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String data = null;
while((data = br.readLine()) != null) {
list.add(data);
}
br.close();
isr.close();
is.close();
if (list.size()!=0){
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if (!s.equals("")&&s.length()!=0){
str = s;
list.remove(i);
break;
}
}
}
if(list.size() != 0) {
FileOutputStream fileOutputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
BufferedWriter bw = new BufferedWriter(outputStreamWriter);
for (String string : list) {
if (!string.equals("")&&string.length()!=0) {
bw.write(string);
bw.newLine();
}
}
bw.flush();
bw.close();
}
return str==null?temp:str;
}
}
Controller
package com.xiaobai.scheduled.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class indexController {
//只要能进这个页面,代表服务运行正常
@GetMapping("/")
public String index(Model model){
model.addAttribute("title","主页标题");
model.addAttribute("content","主页内容");
return "swing";
}
}
主入口
package com.xiaobai.scheduled;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
项目链接
https://github.com/xiaodingfeng/ScheduledSendMail/tree/master
评论区