Spring Boot综合项目实战-邮件管理

邮件管理

一、发文本邮件

1、可以随意填写需要发送的邮箱地址(正确的邮箱地址)

2、可以随意填写文本内容,但不能超过10个字

3、点击退出按钮即退出邮件发送页面

4、点击发送按钮

(1)邮箱地址为空,报出提示语(邮箱地址不能为空)

(2)邮箱格式不正确,报出提示语(邮箱格式不正确)

(3)文本内容为空,报出提示语(文本内容不能为空)

(4)文本内容超过10个字,报出提示语(文本超过10个字)

二、发附件邮件(随意选择本地附件,中文名不能乱码)

1、可以随意填写需要发送的邮箱地址(正确的邮箱地址)

2、随意选择本地电脑的附件发送

三、发图片邮件(随意选择本地图片,中文名不能乱码)

1、可以随意填写需要发送的邮箱地址(正确的邮箱地址)

2、随意选择本地电脑的图片发送

四、发模板邮件

1、可以随意填写需要发送的邮箱地址(正确的邮箱地址)

2、可以随意填写文本内容

五、发定时邮件

1、每隔30秒发送一次定时邮件


引入依赖

<!-- Spring Boot Thymeleaf Starter - Thymeleaf模板引擎依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- Spring Boot Starter Mail - 邮件服务依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>


全局配置

#QQ邮箱邮件发送服务配置
spring.mail.host=smtp.qq.com
spring.mail.port=587

# 配置个人QQ账户和密码(密码是加密后的授权码)
#spring.mail.username=123456789@qq.com
#spring.mail.password=asdfghjklzxcvbnm


邮箱发送页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>发送邮件</title>
<link rel="stylesheet" href="video/Dome.css">
<script th:src="@{/assets/js/jquery.min.js}"></script>
</head>
<body style="background: #9de0f6">

<font size="5px" color="#6a5acd">

<input style="width: 80px;height: 40px;background: red" type="button" value="退出" οnclick="history.back()">

<div >

<label for="to" >请选择邮箱类型:</label>
<select id="type" style="font-size: 25px">
<option value="1" style="font-size: 25px">文本邮件</option>
<option value="2" style="font-size: 25px">附件邮件</option>
<option value="3" style="font-size: 25px">图片邮件</option>
<option value="4" style="font-size: 25px">模板邮件</option>
</select>
</div>


<div >
<input type="hidden" id="token" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<label for="to">邮箱地址:</label>
<input type="email" id="to" placeholder="输入邮箱地址" style="font-size: 22px">
</div>


<div id="subject1" >
<label for="subject">邮箱主题:</label>
<input id="subject" placeholder="输入主题内容" style="font-size: 22px">
</div>



<div id="file1" >
<label for="file">选择附件:</label>
<input type="file" id="file" style="font-size: 22px">
</div>

<div id="image1" >
<label for="image">选择图片:</label>
<input type="file" id="image" accept="image/*" style="font-size: 22px">
</div>


<div id="content1" >
<label for="content">文本内容:</label>
<textarea id="content" placeholder="输入文本内容" style="font-size: 25px"></textarea>
</div>

<!-- <textarea id="content" rows="6" cols="36" placeholder="输入文本内容"></textarea>-->


<div >
<button οnclick="sendEmail()" style="width: 80px;height: 40px;background: mediumspringgreen">发送</button>
</div>

</font>

<script>

document.addEventListener("DOMContentLoaded", function() {
const emailTypeSelect = document.getElementById('type');
function handleEmailTypeChange() {
if (emailTypeSelect.value === '2') { // 当选择的是“附件邮件”
document.getElementById('file1').style.display='block'; //展示上传框
document.getElementById('content1').style.display='none'; //隐藏文本框
document.getElementById('subject1').style.display='block'; //展示主题
document.getElementById('image1').style.display='none'; //隐藏图片框
} else if(emailTypeSelect.value === '1') { //文本邮件
document.getElementById('to').value = '';
document.getElementById('content1').style.display='block'; //展示文本框
document.getElementById('subject1').style.display='block'; //展示主题
document.getElementById('file1').style.display='none'; //隐藏上传框
document.getElementById('image1').style.display='none'; //隐藏图片框
} else if(emailTypeSelect.value === '3'){ //图片邮件
document.getElementById('to').value = '';
document.getElementById('image1').style.display='block'; //展示图片框
document.getElementById('content1').style.display='none'; //隐藏文本框
document.getElementById('subject1').style.display='block'; //展示主题
document.getElementById('file1').style.display='none'; //隐藏上传框
}else if(emailTypeSelect.value === '4'){ //模板邮件
document.getElementById('image1').style.display='none'; //隐藏图片框
document.getElementById('content1').style.display='block'; //展示文本框
document.getElementById('subject1').style.display='block'; //展示主题
document.getElementById('file1').style.display='none'; //隐藏上传框
}
}

// 监听邮件类型下拉框的变化
emailTypeSelect.addEventListener('change', handleEmailTypeChange);

// 在页面加载完成时,调用此函数以应用正确的显示状态
handleEmailTypeChange();
});

function sendEmail() {
const token = document.getElementById('token').value;
const type = document.getElementById('type').value; // 邮件类型
const to = document.getElementById('to').value;
const content = document.getElementById('content').value;
const subject = document.getElementById('subject').value;

const formData = new FormData(); // 创建一个 FormData 对象以发送文件
formData.append('type', type); // 添加邮件类型
formData.append('to', to); // 添加收件人地址
formData.append('content', content); // 添加邮件内容
formData.append('subject', subject); // 添加邮件主题

if (type == 2) { // 如果是附件邮件,添加文件
const file = document.getElementById('file').files[0];
formData.append('file', file);
}
if(type ==3){
const image = document.getElementById('image').files[0];
formData.append('image', image);
}

$.ajax({
url: '/send/text',
type: 'post',
processData: false, // 防止 jQuery 处理 FormData
contentType: false, // 将内容类型设置为 false,jQuery 会自动设置
headers: {
'X-CSRF-TOKEN': token
},
data: formData,
success: function (response) {
alert(response);
},
error: function (response) {
let errorMessage = '发送失败';
if (response && response.responseText) {
let parsedResponse = JSON.parse(response.responseText);
if (parsedResponse && parsedResponse.error) {
errorMessage = parsedResponse.error;
}
}
alert(errorMessage);
}
});
}

</script>
</body>
</html>


模板邮件页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>模板邮件</title>
</head>
<body>
<p style="color: #bc99c4;font-size: 28px">亲爱的用户:</p>
<p style="font-size: 28px;color: #bc99c4">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好!</p>
<p th:text="${content}">[邮件内容]</p>
</body>
</html>


EmailController

package com.itheima.web.emali;

import com.itheima.model.domain.Email;
import com.itheima.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/send")
@CrossOrigin
public class EmailController {

@Autowired
private EmailService emailService;

@PostMapping(value = "/text")
public ResponseEntity<String> sendTextEmail(@RequestParam("to") String to,
@RequestParam("subject") String subject,
@RequestParam("content") String content,
@RequestParam("type") int type,
@RequestParam(value = "file", required = false) MultipartFile file,
@RequestPart(value = "image", required = false) MultipartFile imageFile) {
try {
emailService.sendTextEmail(to,subject,content,type,file,imageFile);
return ResponseEntity.ok("邮件已发送.");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("{\"error\":\"" + e.getMessage() + "\"}");
}
}
}

EmailIndexController

package com.itheima.web.emali;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class EmailIndexController {
//.
@RequestMapping("/emali")
public String index(){


return "email/index";
};
}


Email

package com.itheima.model.domain;


import org.springframework.web.multipart.MultipartFile;

/**
* 邮箱实体..
*/
public class Email {

private String to;//收件人
private String subject;//邮箱主题
private String content;//邮箱内容




public String getTo() {
return to;
}

public void setTo(String to) {
this.to = to;
}

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}
}


EmailService

package com.itheima.service;


import com.itheima.model.domain.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class EmailService {

@Autowired(required = false)
private JavaMailSender emailSender;

@Value("${spring.mail.username}")
private String fromEmail;
@Autowired
private SpringTemplateEngine templateEngine;

/**
* 发送文本邮件、附件邮件、带图片的邮件或使用模板渲染的邮件。
*
* @param to 收件人的电子邮件地址
* @param subject 邮件主题
* @param content 邮件内容
* @param type 邮件类型,1表示文本邮件,2表示附件邮件,3表示带图片的邮件,4表示使用模板渲染的邮件
* @param file 附件文件,仅在type为2时有效
* @param imageFile 图片文件,仅在type为3时有效
* @throws Exception 如果发生任何异常,将抛出异常
*/
public void sendTextEmail(String to, String subject, String content, int type, MultipartFile file, MultipartFile imageFile) throws Exception {
if (to == null || to.isEmpty()) {
throw new Exception("邮箱地址不能为空");
}
if (!isValidEmail(to)) {
throw new Exception("邮箱格式不正确");
}
if (type == 1) {
if (content == null || content.isEmpty()) {
throw new Exception("文本内容不能为空");
}
if (content.length() > 10) {
throw new Exception("文本超过10个字");
}
}
if (type == 1) { //文本邮件..
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail); // 设置发件人
message.setTo(to); //收件人
message.setSubject(subject);//主题
message.setText(content); //内容
emailSender.send(message);
} else if (type == 2) {//附件邮件..
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromEmail); // 设置发件人
helper.setTo(to); //收件人
helper.setSubject(subject); //主题
helper.setText(content); //内容
if (file != null && !file.isEmpty()) {
helper.addAttachment(file.getOriginalFilename(), file); 添加附件到邮件消息中
}
emailSender.send(message); //发送附件
} else if (type == 3) {//图片邮件..
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromEmail); // 设置发件人
helper.setTo(to); //收件人
helper.setSubject(subject); //主题
String imageFilename = MimeUtility.encodeText(imageFile.getOriginalFilename(), "utf-8", "B");
String cid = "imageCid";
helper.setText("<html><body><img src='cid:" + cid + "'></body></html>", true);
helper.addInline(cid, new ByteArrayResource(imageFile.getBytes()), imageFile.getContentType());
emailSender.send(message); //发送图片
} else if (type == 4) {//模板邮件..
Context context = new Context();
context.setVariable("content", content);
// 使用 Thymeleaf 模板引擎渲染 HTML
String process = templateEngine.process("/email/email-template", context);
// 创建邮件消息
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromEmail); // 设置发件人
helper.setTo(to); //收件人
helper.setSubject(subject); //主题
helper.setText(process, true);

// 发送邮件
emailSender.send(message);
}
}

/**
* 检查给定的字符串是否为有效的电子邮件地址。
*
* @param email 要验证的电子邮件地址字符串
* @return 如果电子邮件地址有效则返回true,否则返回false
*/
private boolean isValidEmail(String email) {
String regex = "^(.+)@(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}

/**
* 定时发送邮件
*
* @throws Exception
*/
@Scheduled(fixedRate = 30000) // 30000毫秒 = 30秒
public void sendScheduledEmail() throws Exception {
//定时发送文本邮件
sendTextEmail("123456789@qq.com", //邮箱
"定时邮件", //主题
"定时发送邮件", 1, null, null); //内容
System.out.println("定时邮件发送成功!!!!!!");
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值