基于Maven,spring整合quartz,定时发送邮件

时间:2023-01-28 07:54:32

前段时间刚把工作任务做完,闲来无事,到网上看看资料,发现自己对java quartz定时任务和java发送邮件挺感兴趣,于是借鉴网上的列子写了一个简单的Demo(Maven工程),使用Spring整合quartz实现定时任务,使用java mail实现发送邮件

1. 定时任务的实现

1.1 导jar包,pom.xml中的相关配置如下

<!-- 使用国内的maven仓库 -->
<repositories>
<repository>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<!-- 日志框架jar包依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>
<!-- spring和quartz的jar包依赖 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<!-- java mail的jar包 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.3</version>
</dependency>

1.2 写一个调度器要执行的任务内容的类

public class SendMailScheduler {
private static final Logger LOG = Logger.getLogger(SendMailScheduler.class);
public void work() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
LOG.debug(sdf.format(new Date()));

}
}
1.3 在spring容器中配置quartz

1.3.1 实现JobDetail

    <!-- 第二种方式实现JobDetail 普通类 -->
<bean id="Quartz" class="com.formssi.spring_quartz.SendMailScheduler"></bean>
<bean id="JobDetail2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="Quartz"></property>
<property name="targetMethod" value="work"></property>
</bean>
1.3.2  配置触发器Trigger

 <!-- 触发器的第二种方式 CRON表达式 -->
<bean id="trigger2" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobDetail2"></property>
<!-- 一下配置是每15秒发送执行一次任务 -->
<property name="cronExpression" value="0/15 * * * * ?"></property>
</bean>

1.3.3 配置调度器

<!-- 把触发器加入到任务列表中 -->
<bean id="testScheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="trigger2" />
</list>
</property>
</bean>
1.4 测试任务调度的配置结果(Log4J的配置略过)

基于Maven,spring整合quartz,定时发送邮件

2. 实现邮件发送

2.2 写发送邮件的类,具体看注释

public class SendMail {
private static final Logger LOG = Logger.getLogger(SendMail.class);
private String host = ""; // smtp服务器
private String from = ""; // 发件人地址
private String to = ""; // 收件人地址
private String[] attachmentPath = null; // 附件地址
private String user = ""; // 用户名
private String pwd = ""; // 密码
private String subject = ""; // 邮件标题
private int status = 0; // 发送结果:0-成功,1-失败
private String htmlContent = ""; //若果发送的是html格式的邮件,这是html内容

private static final Logger logger = Logger.getLogger(SendMail.class);
public void setAddress(String from, String to, String subject) {
this.from = from;
this.to = to;
this.subject = subject;
}
public void setAttachmentPath(String[] attachmentPath) {
this.attachmentPath = attachmentPath;
}

public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
public int sendMail(String user, String pwd, String host) {
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties prop = new Properties();
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.port","25");
prop.put("mail.transport.protocol", "smtp");

// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getInstance(prop);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
try {
//设置发件人地址
message.setFrom(new InternetAddress(from));
//设置收件人地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
//设置邮件标题
message.setSubject(subject);
Multipart mp = new MimeMultipart();
// 设置邮件的文本内容
BodyPart bodyPart = new MimeBodyPart();
//邮件正文(html形式)
bodyPart.setContent(htmlContent, "text/html; charset=utf-8");
mp.addBodyPart(bodyPart);
//设置邮件附件
for (String filePath:attachmentPath) {
bodyPart= new MimeBodyPart();
File attachment = new File(filePath);
if (!attachment.exists()) {
LOG.warn("文件:"+attachment+"不存在!");
status = 1;
return status;
} else{
DataSource ds = new FileDataSource(attachment);
bodyPart.setDataHandler(new DataHandler(ds));
// 添加附件的标题
// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
bodyPart.setFileName("=?GBK?B?"
+ enc.encode(attachment.getName().getBytes()) + "?=");
mp.addBodyPart(bodyPart);
message.setContent(mp);
}
}
message.saveChanges();
//创建Transport对象
Transport transport = session.getTransport("smtp");
//连接服务器
transport.connect(host, user, pwd);
//发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("发送失败!");
}
return status;
}
}

2.2 在任务类中调用发送邮件的方法

public class SendMailScheduler {
private static final Logger LOG = Logger.getLogger(SendMailScheduler.class);
public void work() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
LOG.debug(sdf.format(new Date()));
SendMail sendmail = new SendMail();
//设置发件地址和收件地址及主题
sendmail.setAddress("1300880****@163.com", "huang**o@formssi.com", "哈哈!逗你玩!");
//设置附件
sendmail.setAttachmentPath(new String[]{"D:/logs/test.log", "D:/picture/test.PNG"});
//设置html内容
StringBuffer content = new StringBuffer();
content.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">")
.append("<html>")
.append("<head>")
.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">")
.append("<title>测试邮件</title>")
.append("<body>")
.append("<h2>尊敬的xxx,您好,您需要的信息如下:</h2>")
.append("<ol>")
.append("<li>xxxxx1</li>")
.append("<li>xxxxx2</li>")
.append("<li>xxxxx2</li>")
.append("</ol>")
.append("</body>")
.append("</head>")
.append("</html>");
sendmail.setHtmlContent(content.toString());
//调用发送邮件方法
int status = sendmail.sendMail("13008807015", "********", "smtp.163.com");
if (status == 1) {
LOG.error("发送失败");
} else {
LOG.info("发送成功");
}
}
}
2.3 测试发送结果

基于Maven,spring整合quartz,定时发送邮件

下载Demo链接: 点击打开链接