spring定时器和spring javaMail

本文介绍如何使用Spring框架配置定时任务并发送邮件通知。通过Quartz实现定时调度,利用JavaMailSender发送邮件,并借助jExcelAPI生成Excel附件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring内置了定时器,其实是对java.util.timer的一个自己的实现。通过它可以定时的做一些任务,比如定时的发送邮件,同样的,spring对javaMail也进行了一些封装。看配置文件。

 

这个是配置文件mail.property

mail.username=xxxx
mail.password=xxxx
mail.host=mail.mchz.com.cn
mail.from=xxxx@mchz.com.cn

mail.smtp.auth=true
mail.debug=true

resource=/xls
ipaddress=172.16.4.110
 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
		xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	 
	<import resource="applicationContext-propertyConfigurer.xml"/>
	
    
    <!-- 定时调度 -->
    <bean id="LoginAuditService" class="com.hzmc.capaa.business.search.impl.LoginAuditSendMailService">
    	<property name="from" value="${mail.from}"/>
    	<property name="resource" value="${resource}"/>
    	<property name="ipaddress" value="${ipaddress}"/>
    </bean>
    
     <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    	<property name="targetObject" ref="LoginAuditService"/>
    	<property name="targetMethod" value="sendLoginAuditMailReport"/>
    </bean>
           	
    <bean id="jobTiger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="jobDetail"/>
        <property name="cronExpression" value="0 45 8  * * ?"/>
    </bean>
          
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="jobTiger"/>
			</list>
		</property>
		<property name="autoStartup" value="true"/>
	</bean>
	
	<!-- 邮件配置 -->
	<bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="${mail.host}"/>
		<property name="username" value="${mail.username}"/>
		<property name="password" value="${mail.password}"/>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
				<prop key="debug">${mail.debug}</prop>
			</props>
		</property>				
	</bean>
</beans>

 下面是业务类,负责发邮件的业务类。代码包含用jexcelAPI生成excel文件

package com.hzmc.capaa.business.search.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.WritableFont;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import com.hzmc.capaa.business.auditselect.AuditSelectManager;
import com.hzmc.capaa.business.search.LoginAuditSearchManager;
import com.hzmc.capaa.business.userconfig.UserConfigFileManager;
import com.hzmc.capaa.domain.persistence.audit.AuditSelect;
import com.hzmc.capaa.domain.persistence.search.LoginAuditSearch;
import com.hzmc.capaa.domain.persistence.userconfig.UserConfigFile;
import com.hzmc.capaa.web.util.GetCurrentDateTime;

public class LoginAuditSendMailService {

	@Autowired
	private JavaMailSender sender;

	@Autowired
	private UserConfigFileManager userConfigFileManger;

	@Autowired
	private LoginAuditSearchManager loginAuditSearchManager;

	@Autowired
	private AuditSelectManager auditSelectManager;

	private String from;
	
	private String ipaddress;
	
	private Resource resource;

	public void setFrom(String from) {
		this.from = from;
	}

	public void sendLoginAuditMailReport() {
		getCapaaUserList();
	}

	@SuppressWarnings("unchecked")
	public void getCapaaUserList() {
		List<UserConfigFile> userList = this.userConfigFileManger
				.getUserConfigFileList();
		for (UserConfigFile user : userList) {
			String name = user.getCapaaUser();
			String moudle = user.getAuditModule();
			String tomail = user.getUserEmail();
			String title = "您的关于登录审计的定制信息";
			String content = "你订阅的审计信息已经收到,请点击下面的链接下载或查看!\n";
			String[] moudles = moudle.split(";");
			for (String model : moudles) {
				if (model.indexOf("a") != -1) { //标示关注登录审计模块
					LoginAuditSearch loginAudit = this.loginAuditSearchManager
							.checkIsExists(name);
					if (loginAudit == null) {
						// 直接默认处理
						getLoginAuditDataList(name,"1=1",tomail,title,content);
					} else {
						// 加上默认的审计条件
						String dbUser=loginAudit.getDbUser();
						BigDecimal dbId=loginAudit.getDbId();
						String osUser=loginAudit.getOsUser();
						String realUser=loginAudit.getRealUser();
						String ipAddress=loginAudit.getIpAddress();
						String appName=loginAudit.getApplication();
						String timeStamp=loginAudit.getTimestamp();
						
						String whereFilter = "1=1";
						if (dbUser != null && !"".equals(dbUser)) {
							whereFilter += " and dbuser ='" + dbUser + "'";
						}

						if (dbId != null && !"".equals(dbId)) {
							whereFilter += " and dbid='" + dbId + "'";
						}
						if (osUser != null && !"".equals(osUser)) {
							whereFilter += " and osuser like '%" + osUser + "%'";
						}

						if (realUser != null && !"".equals(realUser)) {
							whereFilter += " and realuser like '%" + realUser + "%'";
						}
						if (ipAddress != null && !"".equals(ipAddress)) {
							whereFilter += " and IP_ADDRESS like '%" + ipAddress + "%'";
						}
						if (appName != null && !"".equals(appName)) {
							whereFilter += " and APP_NAME like '%" + appName + "%'";
						}
						if (timeStamp != null && !"".equals(timeStamp)) {
							whereFilter += " and TIMESTAMP >= to_date('" + timeStamp
									+ "','yyyy-mm-dd HH24:mi')";
						}
						
						getLoginAuditDataList(name,whereFilter,tomail,title,content);
						
					}
				}
			}

		}
	}

	@SuppressWarnings("unchecked")
	private void getLoginAuditDataList(String name,String whereFilter,String tomail,String title,String content) {
		Map map = new HashMap();
		map.put("ipAddress", whereFilter);
		map.put("dbId", new BigDecimal(0));
		map.put("countNumber", new Integer(200));
		map.put("clientId", UUID.randomUUID().toString());
		List<AuditSelect> list = this.auditSelectManager
				.getAuditSelectByPages(map);
		String fileName = name
				+ GetCurrentDateTime.getCurrentTime()+".xls";
		
		if (list != null) {
			try {
				if(!resource.getFile().getAbsoluteFile().exists()){
					File f=new File(resource.getFile().getAbsolutePath());
					f.mkdir();
				}
				extExcel(list, resource.getFile().getAbsolutePath()+"\\"+fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		content="http://"+ipaddress+":8082/capaa/xls/"+fileName;
		sendMailtoCapaaUser(tomail,title,content);
	}

	@SuppressWarnings("unchecked")
	public void extExcel(List<AuditSelect> loginList, String fileName) {
		File file = new File(fileName);
		jxl.write.WritableWorkbook wwb = null;
		jxl.write.WritableSheet ws = null;
		try {
			file.createNewFile();
			wwb = Workbook.createWorkbook(file);
			ws = wwb.createSheet("LoginAuditSheet", 0);
			jxl.write.Label labela = new jxl.write.Label(0, 0, "数据库用户");
			jxl.write.Label labelb = new jxl.write.Label(1, 0, "IP地址");
			jxl.write.Label labelc = new jxl.write.Label(2, 0, "应用程序");
			jxl.write.Label labeld = new jxl.write.Label(3, 0, "登录时间");
			jxl.write.Label labele = new jxl.write.Label(4, 0, "响应行为");
			jxl.write.Label labelf = new jxl.write.Label(5, 0, "审计级别");
			jxl.write.Label labelg = new jxl.write.Label(6, 0, "错误性息");

			ws.addCell(labela);
			ws.addCell(labelb);
			ws.addCell(labelc);
			ws.addCell(labeld);
			ws.addCell(labele);
			ws.addCell(labelf);
			ws.addCell(labelg);
			
			for(int i=1;i<loginList.size()+1;i++){
				
				AuditSelect loginAudit=(AuditSelect)loginList.get(i-1);
				String dbUser = loginAudit.getDbUser();
				String ipAddress = loginAudit.getIpAddress();
				String appLication = loginAudit.getAppName();
				String loginTime = loginAudit.getTimestamp().toString();
				String reaction = loginAudit.getAuditClass();
				String auditLevel = loginAudit.getAuditLevel().toString();
				String errInfo = loginAudit.getErrMsg();
				
				
				jxl.write.Label lable1 = new jxl.write.Label(0, i, dbUser);
				jxl.write.Label lable2 = new jxl.write.Label(1, i, ipAddress);
				jxl.write.Label lable3 = new jxl.write.Label(2, i, appLication);
				jxl.write.Label lable4 = new jxl.write.Label(3, i, loginTime);
				jxl.write.Label lable5 = new jxl.write.Label(4, i, reaction);
				jxl.write.Label lable6 = new jxl.write.Label(5, i, auditLevel);
				jxl.write.Label lable7 = new jxl.write.Label(6, i, errInfo);
				
				ws.addCell(lable1);
				ws.addCell(lable2);
				ws.addCell(lable3);
				ws.addCell(lable4);
				ws.addCell(lable5);
				ws.addCell(lable6);
				ws.addCell(lable7);
				
				
			}

			jxl.write.WritableFont wfc = new jxl.write.WritableFont(
					WritableFont.ARIAL, 20, WritableFont.BOLD, false,
					UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.GREEN);

			jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(
					wfc);

			wcfFC.setBackground(jxl.format.Colour.RED);
			wwb.write();
			wwb.close();
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	private void sendMailtoCapaaUser(String tomail, String title, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(tomail);
		message.setSubject(title);
		message.setText(content);
		sender.send(message);
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}

	public void setIpaddress(String ipaddress) {
		this.ipaddress = ipaddress;
	}

}
 //假如是发送html邮件,那么用MimeMessage 
               MimeMessage msg = sender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
			
			helper.setFrom(from);
			helper.setTo(tomail);
			helper.setSubject(title);
			helper.setText(content,true);
			sender.send(msg);
		} catch (MessagingException e) {
			e.printStackTrace();
		} 
内容概要:该研究通过在黑龙江省某示范村进行24小时实地测试,比较了燃煤炉具与自动/手动进料生物质炉具的污染物排放特征。结果显示,生物质炉具相比燃煤炉具显著降低了PM2.5、COSO2的排放(自动进料分别降低41.2%、54.3%、40.0%;手动进料降低35.3%、22.1%、20.0%),但NOx排放未降低甚至有所增加。研究还发现,经济性便利性是影响生物质炉具推广的重要因素。该研究不仅提供了实际排放数据支持,还通过Python代码详细复现了排放特征比较、减排效果计算结果可视化,进一步探讨了燃料性质、动态排放特征、碳平衡计算以及政策建议。 适合人群:从事环境科学研究的学者、政府环保部门工作人员、能源政策制定者、关注农村能源转型的社会人士。 使用场景及目标:①评估生物质炉具在农村地区的推广潜力;②为政策制定者提供科学依据,优化补贴政策;③帮助研究人员深入了解生物质炉具的排放特征技术改进方向;④为企业研发更高效的生物质炉具提供参考。 其他说明:该研究通过大量数据分析模拟,揭示了生物质炉具在实际应用中的优点挑战,特别是NOx排放增加的问题。研究还提出了多项具体的技术改进方向政策建议,如优化进料方式、提高热效率、建设本地颗粒厂等,为生物质炉具的广泛推广提供了可行路径。此外,研究还开发了一个智能政策建议生成系统,可以根据不同地区的特征定制化生成政策建议,为农村能源转型提供了有力支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值