`
chenhua_1984
  • 浏览: 1246361 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

spring定时器和spring javaMail

阅读更多

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();
		} 
分享到:
评论

相关推荐

    Spring javaMail发送文本邮件实例

    导入到Myeclipse 即可运行 测试使用的是QQ邮箱 在application.xml中配置的发送邮箱 要到邮箱中设置 POP3/SMTP服务为开。项目不部署到tomcat后启动服务,然后运行test.java 就发送了,。绝对可以发送

    Spring实现JavaMail邮件发送功能

    而Spring框架通过提供`JavaMailSender`接口,将JavaMail与Spring的IoC(Inversion of Control)容器集成,简化了邮件服务的配置和使用。 1. **配置JavaMailSender** 在Spring中,我们需要配置`JavaMailSender`实例...

    spring结合javamail开发文档

    ### Spring结合JavaMail开发文档知识点详解 #### 一、JavaMail快速入门 ##### 1.1 JavaMail概述 JavaMail是一套由Sun Microsystems定义的API集合,主要用于在Java应用程序中发送与接收电子邮件。尽管JavaMail功能...

    Spring整合JavaMail发送qq邮件

    通过上述步骤,你已经成功地整合了Spring和JavaMail,实现了通过QQ邮箱发送邮件的功能。这个过程非常简单,适合初学者学习和实践。在实际项目中,你可能还需要考虑异常处理、模板邮件、多语言支持等更复杂的需求。...

    spring+javamail代码示例

    本示例将深入探讨如何结合Spring框架和JavaMail API来发送电子邮件,这在许多业务场景中非常实用,如通知服务、用户验证等。 首先,我们需要了解`EmailSender`类。这个类通常会包含实现邮件发送的核心逻辑。在...

    在spring利用javamail,quartz定时发送邮件

    通过上述步骤,我们不仅了解了如何在Spring环境中结合JavaMail和Quartz实现定时邮件发送,而且还深入探索了Spring框架如何简化JavaMail API的使用,以及Quartz如何提供灵活的定时任务调度能力。这种技术组合为Web...

    javamail+spring

    JavaMail和Spring是两个在Java开发中非常重要的库。JavaMail主要用于处理电子邮件的发送和接收,而Spring则是一个广泛使用的框架,它提供了依赖注入、面向切面编程、数据访问、事务管理等多种功能。将JavaMail集成到...

    spring javamail 来发送动态生成的3D图象.doc

    在本文中,我们将探讨如何使用Spring和JavaMail发送动态生成的3D图像,特别是针对Web应用环境。在处理高流量的Web应用时,我们需要避免在服务器上存储大量的3D图像,以节省存储空间。这里的关键是利用JavaMail的特性...

    spring依赖包,spring自行整合的市面上几乎和spring有关的jar包

    标题中的“spring依赖包”指的是Spring框架所需要的一系列外部库,这些库被Spring用来扩展其功能,以便与其他流行的技术和标准进行集成。Spring作为一个全面的轻量级应用框架,其核心特性可以支持应用程序的配置和...

    SpringUseJavaMailSendEmail(spring使用javamail发送邮件的例子)

    总结起来,Spring结合JavaMail API发送邮件的过程主要包括:配置`JavaMailSender` bean,创建邮件消息对象,设置邮件内容和属性,最后通过`JavaMailSender`实例发送邮件。通过这种方式,开发者可以轻松地在Spring...

    spring+quartz+javamail定时发送邮件

    1. 引入相关依赖:在项目中,你需要引入Spring、Quartz和JavaMail的依赖库,这通常通过Maven或Gradle来实现。 2. 配置Spring:在Spring的配置文件(如`applicationContext.xml`)中,你需要声明Quartz的相关bean,...

    JavaMail实现源代码和jar包

    JavaMail 是一个开源的 Java API,它允许 Java 程序员通过 SMTP、POP3 或 IMAP 协议发送、接收和管理电子邮件。这个压缩包包含了一组与 JavaMail 相关的源代码和必要的库文件,使得开发者可以快速地理解和实现邮件...

    struts2+spring3.0+mybatis3.0.4集成的邮件发送实例(可上传附件)

    总之,这个实例结合了Struts2、Spring和Mybatis的强大功能,提供了一个完整的邮件发送系统,包括邮件的创建、附件上传和数据库操作。对这个实例的学习和实践,可以帮助开发者深入理解Java企业级应用的开发流程和技巧...

    Spring.pdf

    6. 降低 JavaEE API 的使用难度:Spring 对 JavaEE API(如 JDBC、JavaMail、远程调用等)进行了薄薄的封装层,使这些 API 的使用难度大为降低。 7. Spring 框架源码是经典学习范例:Spring 的源代码设计精妙、结构...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.1.2. Spring AOP的功能和目标 6.1.3. Spring的AOP代理 6.2. @AspectJ支持 6.2.1. 启用@AspectJ支持 6.2.2. 声明一个切面 6.2.3. 声明一个切入点(pointcut) 6.2.3.1. 切入点指定者的支持 6.2.3.2. 合并切入点...

    spring集成邮件服务

    下面将详细阐述Spring如何与JavaMail API结合,实现邮件服务的集成。 首先,我们需要理解JavaMail API。JavaMail是一个开源库,它允许Java应用程序发送和接收电子邮件。它提供了一系列接口和类,用于操作邮件服务器...

    JavaMail Spring

    JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输。 这里提供一个操作JavaMail的例子,可以发送文本邮件,HTML邮件,附件,抄送...

    spring各种邮件发送

    为了使用JavaMail中的一些特色, 比如MIME类型的信件, Spring提供了MailSender的一个子接口, 即org.springframework.mail.javamail.JavaMailSender。Spring还提供了一个回调接口org.springframework.mail.javamail....

Global site tag (gtag.js) - Google Analytics