前几天,需要做一个功能就是 客户使用我们公司的设备的时候 ,每天固定一个时间点 ,我们定时发送该设备的数据到客户邮箱,让客户了解自己设备的一个情况,由于代码不能上传,就把当时我开始搭建开发而写的一个demo记录下来,实现的原理是一样的,非常之简单.
一.创建一个springboot的项目
项目结构图:
首先,我们先测试邮件发送
controller层
package com.csq.study.controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import com.csq.study.service.SendMailService;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.thymeleaf.context.Context;
import java.io.File;
import java.util.ArrayList;
@RestController
public class SendMailController {
@Autowired
private SendMailService sendMailService;
@Autowired
private TemplateEngine templateEngine;
@RequestMapping(value = "/sendOne",method = RequestMethod.GET)
public String sendOne() throws MessagingException {
//简单邮件
//测试企业邮箱
sendMailService.sendTxtMail1("*******@163.com","简单的文字介绍","我是一封简单的测试邮件");
return "sendOne发送成功";
}
@RequestMapping(value = "/sendTwo",method = RequestMethod.GET)
@ResponseBody
public String sendTwo() throws MessagingException {
//模板邮件
//测试163邮箱
Context ct = new Context();
ct.setVariable("username","我是程小清呀!");
sendMailService.sendTxtMail2("******@163.com","附带标题内容等邮件",templateEngine.process("mail01",ct));
return "sendTwo发送成功";
}
@RequestMapping(value ="/sendThree",method = RequestMethod.GET)
public String sendThree() throws MessagingException {
//模板邮件,带附件
Context ct = new Context();
ct.setVariable("username", "我是程小清呀!(附带两首诗歌)");
ArrayList<File> files = new ArrayList<>();
File file = new File("/Users/csq/Desktop/mail.txt");
boolean exists = file.exists();
if (exists) {
files.add(file);
sendMailService.sendTxtMail3("******@163.com", "带有附件的测试邮件", templateEngine.process("mail02", ct), files);
return "sendThree发送成功";
}
return "sendThree发送失败";
}
}
service层
package com.csq.study.service;
import java.io.File;
import java.util.List;
public interface SendMailService {
void sendTxtMail1(String accept, String topic, String content) ;
void sendTxtMail2(String accept, String topic, String content) ;
void sendTxtMail3(String accept, String topic, String content, List<File> files) ;
}
实现类
package com.csq.study.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
@Service
public class SendMailServiceImpl implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
/**
* 邮件的发送方
*/
@Value("${spring.mail.username}")
private String sendFrom;
@Override
public void sendTxtMail1(String accept, String topic, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sendFrom);
message.setTo(accept);
message.setSubject(topic);
message.setText(content);
javaMailSender.send(message);
}
@Override
public void sendTxtMail2(String accept, String topic, String content) {
// TODO Auto-generated method stub
MimeMessage message = javaMailSender.createMimeMessage();
//true表示需要创建一个multipart message
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sendFrom);
helper.setTo(accept);
helper.setSubject(topic);
helper.setText(content, true);
javaMailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void sendTxtMail3(String accept, String topic, String content, List<File> files) {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper mh = new MimeMessageHelper(message, true);
mh.setFrom(sendFrom);
mh.setTo(accept);
mh.setSubject(topic);
mh.setText(content, true);
//添加附件
for (File file : files) {
mh.addAttachment(file.getName(), new FileSystemResource(file));
}
javaMailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
application.properties
#设置服务端口
server.port=9800
# Email配置属性
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=***@qq.com
#切记此处需要开启pom3的时候的验证码不是邮箱的密码
spring.mail.password= 你的验证码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
mail01
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>邮件格式</title>
</head>
<body>
<h3><span th:text="${username}"></span>,你好!</h3>
<p style="color: red;">这是一封测试邮件。</p>
</body>
</html>
mail02
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>测试邮件2</title>
</head>
<body>
<h3><span th:text="${username}"></span>,你好!</h3>
<p>这是一封含有附件的邮件,请查收!</p>
</body>
</html>
启动项目访问:
去查我们的邮箱是否有新邮件
含附件的邮件
可以看到已经收到邮件.这就说明邮件发送功能是通的 ,那么我们稍加改动就可以做一个定时发送
新增一个类
SendMailTask
package com.csq.study.task;
import com.csq.study.service.SendMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@Component
public class SendMailTask {
private static final Logger logger = LoggerFactory.getLogger(SendMailTask.class);
@Autowired
private SendMailService sendMailService;
@Autowired
private TemplateEngine templateEngine;
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd:hh:mm:ss");
//
// @Scheduled(cron = "*/59 * * * * ?")
// public String SendMail() {
// logger.info("定时发送短信在" + sf.format(new Date()) + "被触发-->");
// sendMailService.sendTxtMail1("****.song@dilatoit.com", "简单的文字介绍", "我是一封简单的测试邮件");
// return "SendMail发送成功";
//
// }
@Scheduled(cron = "*/30 * * * * ?")
public String SendMail01() {
logger.info("定时发送邮件在" + sf.format(new Date()) + "被触发-->");
//模板邮件,带附件
Context ct = new Context();
ct.setVariable("username", "我是程小清呀!(附带两首诗歌)");
ArrayList<File> files = new ArrayList<>();
File file = new File("/Users/csq/Desktop/mail.txt");
boolean exists = file.exists();
if (exists) {
files.add(file);
sendMailService.sendTxtMail3("*******@163.com", "带有附件的测试邮件", templateEngine.process("mail02", ct), files);
return "sendThree发送成功";
}
return "sendThree发送失败";
}
}
切记,在启动类上添加@EnableScheduling注解
这样 我们在启动项目,就可以看到我们的定时任务触发了
查看控制台:
再去看邮箱
有两封下午3点28发送的,到此,功能完成,非常简单!!
温馨提示:由于我在做测试时候想要快速查看定时发送功能是否好使,改成每5秒发送一次,结果,被腾讯检测出来有攻击邮箱行为,然后被限制发送,所以这个注意一点...