java定时发送邮件(带附件)总结

上一星期的总结:

做了一个算不上项目的小东西,实现了统计mongodb数据库里的信息,将每天,上周7天和上月N天的信息在excel中生成,然后在每月1号,每周一和每天将excel表以email附件的方式发送到统计人员的邮箱里。

首先maven中配置所需依赖:

使用poi生成excel所需:

      <!--  excel-poi -->
       <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi</artifactId>
         <version>3.10-beta2</version>
       </dependency>

在生成emai时,如果是使用IDE工具中自带的生成emai的jar包时,在发送email还是什么时候会出现异常or邮件无主题or乱码什么的,具体记得不太清了:

所以需要使用我们自己引入的email的jar包,并排除myeclipse中的jar包来防止jar包冲突,如下:

       <!--  email -->
       <dependency>
         <groupId>javax.mail</groupId>
         <artifactId>mail</artifactId>
         <version>1.4.7</version>
       </dependency>

       <!-- 排除依赖 -->
      <dependency>
  <groupId>org.apache.ws.commons.axiom</groupId>
  <artifactId>axiom-api</artifactId>
  <version>1.2.14</version>
  <exclusions>
   <exclusion>
           <groupId>org.apache.geronimo.specs</groupId>
           <artifactId>geronimo-javamail_1.4_spec</artifactId>
        </exclusion>
  </exclusions>
 </dependency>

 

下面开始代码总结

 

步骤一:java操作mongodb数据库,统计信息

具体也就是从数据库中拿出想要的信息,我实在统计信息,增删改都不需要,只要查询就可以了,还是比较简单的!

首先:连接数据库中的表:

之后对数据库进行操作:语句如下:

连接数据库表:我连接的是数据库中的Logger表:

DBCollection collection = GetConnection.getCollection("logger");

之后就是拿出自己想要的东西了,加条件:

DBObject query = new BasicDBObject();

query.put("device", mobile);

query.put("city", "大连");

就是拿出表中城市是“大连”,设备型号是手机类型的数据,然后自己可以在后面依次put来添加条件;

 

当想拿出指定范围内的数据的时候使用:一long型日期为例

query.put("date",new BasicDBObject("$gte",LongStartDate).append("$lte",LongEndDate));

就是拿出时间在LongStartDate之后再LongEndDate之前的数据,类似于sql1的beween;

 

在之后比如要查询用户的id是1和2的用户,使用in

query.put("id",new BasicDBObject("$in",new Integer[]{1,2}));

 

最后就是拿出结果了:

如果不用去重的话:

int num = collection.count(query);统计用户数量或拿出所有用户 

Gson gson = new Gson();

List<Logger> list = new ArrayList<Logger>();
  DBCursor cursor = collection.find();
  try{
   while(cursor.hasNext()) {
    DBObject element = cursor.next();
    Logger logger = gson.fromJson(element.toString(), Logger.class);
    list.add(logger);
   }
  }finally{
   cursor.close();
  }

在这里我的实体类是Loger,gson帮助把读出的一条信息转换成Logger类型的数据来存储;

 

去重的话使用distinct;

其余添加选择条件如上,最后使用

List<String> list = collection.distinct("name",query);

这里返回的直接是一个去重name的String类型集合而不是整个用户的集合,之后.size()方法取出数量

这样基本上可以从mongodb数据库中拿出自己想要的数据了。

 

附上一句话:能在数据库中处理的信息最好在数据库中处理,方便快捷还省内存!!

不然数据量大的时候出抛出各种JVM异常和内存溢出

 

 

 

步骤二:

把从数据库中拿出的信息添加到excel表格中,其实也就是为每个表格设置一个值,还是比较简单的,

下面是一个简单模板:

 

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
 
 
/***********************************************************************   
 *   
 *   @copyright       Copyright: 2012     
 *   @creator         sinbong.com  
 ***********************************************************************/ 
public class poiCreate { 
 
    /**
     * @param args
     */ 
    public static void main(String[] args) throws Exception { 
        //创建一个EXCEL 
        Workbook wb = new HSSFWorkbook(); 
        DataFormat format = wb.createDataFormat(); 
        CellStyle style; 
        //创建一个SHEET 
        Sheet sheet1 = wb.createSheet("产品清单"); 
        String[] title = {"编号","产品名称","产品价格","产品数量","生产日期","产地","是否出口"}; 
        int i=0; 
        //创建一行 
        Row row = sheet1.createRow((short)0); 
        //填充标题 
        for (String  s:title){ 
            Cell cell = row.createCell(i); 
            cell.setCellValue(s); 
            i++; 
        } 
        Row row1 = sheet1.createRow((short)1); 
        //下面是填充数据 
        row1.createCell(0).setCellValue(20071001); 
        row1.createCell(1).setCellValue("金鸽瓜子"); 
        //创建一个单元格子 
        Cell cell2=row1.createCell(2); 
        // 填充产品价格 
        cell2.setCellValue(2.45); 
        style = wb.createCellStyle(); 
        style.setDataFormat(format.getFormat("#.##")); 
        //设定样式 
        cell2.setCellStyle(style); 
        // 填充产品数量 
        row1.createCell(3).setCellValue(200); 
        /*  
         * 定义显示日期的公共格式  
         * 如:yyyy-MM-dd hh:mm  
         * */ 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");    
        String newdate = sdf.format(new Date());  
        // 填充出产日期    
        row1.createCell(4).setCellValue(newdate); 
        row1.createCell(5).setCellValue("陕西西安"); 
        /*  
         * 显示布尔值  
         * */  
        row1.createCell(6).setCellValue(true);
        row1.createCell(7).setCellValue("777");
        /*  
         * 合并单元格  
         * 通过writablesheet.mergeCells(int x,int y,int m,int n);来实现的  
         * 表示将first row, last row,first column,last column
         *   
         * */   
        Row row2 = sheet1.createRow((short) 2); 
         Cell cell3 = row2.createCell((short) 0); 
         cell3.setCellValue("合并了三个单元格"); 
// CellRangeAddress(int firstRow, int lastRow,
//         int firstCol, int lastCol)   先行后列
        sheet1.addMergedRegion(new CellRangeAddress(2,2,0,2)); 
        row2.createCell(3).setCellValue("是第三个吗?");
         
        FileOutputStream fileOut = new FileOutputStream("d:\\test.xls"); 
        wb.write(fileOut); 
        fileOut.close(); 
 
 
    } 
 
}

 

根据上面的代码来就可以,复制到自己的myeclipse运行下在对比d盘下test.xls文件基本上自己就可以写了!

想设置单元格颜色的话使用的是:HSSFCellStyle

例子:

Cell cell2 = row.createCell(2);
   cell2.setCellValue("mobile");
   HSSFCellStyle cellStyle = (HSSFCellStyle) workbook.createCellStyle();
   cellStyle.setFillForegroundColor(HSSFColor.BLUE.index); //設置顏色為藍色
   cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
   cell2.setCellStyle(cellStyle);

//CellRangeAddress(firstRow, lastRow, firstCol, lastCol)
   sheet1.addMergedRegion(new CellRangeAddress(0, 0, 2, 20));

 

这段代码意思是:创建了一个单元格,单元格内容:mobile;设置字体颜色为蓝色;这个单元格合并了从第3列到第21列的单元格。

想设置漂亮一点的报表可以自己搜下这个类的各种定义样式的方法。。

 

 

 

步骤三:

定时发送邮件:

 

主要用到的也就三样:

1.监听器 :    javax.servlet.ServletContextListener 

2.定时器:  java.util.TimerTask

3.在web.xml 中配置监听器

创建一个类实现ServletContextListener  接口

 

import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.shiyimm.statistics.util.HandleTime;

public class MyTimerTask implements ServletContextListener {
 private Timer timer = null;

 public void contextDestroyed(ServletContextEvent event) {
  timer.cancel();
  event.getServletContext().log("定时器销毁");
 }

 public void contextInitialized(ServletContextEvent event) {
  // 在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
  timer = new Timer(true);
  
  event.getServletContext().log("定时器已启动");// 添加日志,可在tomcat日志中查看到
  // 调用exportHistoryBean,0表示任务无延迟,5*1000表示每隔5秒执行任务,60*60*1000表示一个小时;
  timer.schedule(new SendEmail(event.getServletContext()), 0,60*60*1000*24);


 }
}

 

 

再创建一个类继承TimerTask类

 

public class SendEmail extends TimerTask 
{ 
 private ServletContext context = null; 
 
 public SendEmail(ServletContext context) 
 { 
  this.context = context; 
 } 
 
 @Override 
 public void run() 
 { 
      /*
      * 以下为javamail的邮件发送
      */

       System.out.println("正在发送邮件");

        Properties props=new Properties();
        props.put("mail.smtp.host","smtp.163.com");//发件人使用发邮件的电子信箱服务器我使用的是163的服务器
        props.put("mail.smtp.auth","true"); //这样才能通过验证
        Session s=Session.getInstance(props);
        s.setDebug(true);

        MimeMessage message=new MimeMessage(s);

        //给消息对象设置发件人/收件人/主题/发信时间
        InternetAddress from=new InternetAddress("daida@163.com");  //发邮件的出发地(发件人的信箱),这是我的邮箱地址,使用请改成你的有效地址
        message.setFrom(from);
        InternetAddress to=new InternetAddress(tto);// tto为发邮件的目的地(收件人信箱)

        message.setRecipient(Message.RecipientType.TO,to);
        message.setSubject(ttitle);// ttitle为邮件的标题
        message.setSentDate(new Date());
        BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
        mdp.setContent(tcontent,"text/html;charset=utf-8");//给BodyPart对象设置内容和格式/编码方式tcontent为邮件内容
        Multipart mm=new MimeMultipart();//新建一个MimeMultipart对象用来存放BodyPart对
        //象(事实上可以存放多个)
        mm.addBodyPart(mdp);//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
        message.setContent(mm);//把mm作为消息对象的内容

        message.saveChanges();
        Transport transport=s.getTransport("smtp");
        transport.connect("smtp.163.com","daida","789-jik");//发邮件人帐户密码,此外是我的帐户密码,使用时请修改。
        transport.sendMessage(message,message.getAllRecipients());
        transport.close();
    }        
   } 
      catch (Exception e) 
      {
    e.printStackTrace();
   }       
     }    
 }
}

 

自己写的类有太多工具类要引用,就不贴了,上面这个也是我上星期跟着学的例子,还是挺好的。

 

最后

下面是配置文件中添加监听器:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <listener>
   <listener-class>com.shiyimm.statistics.email.MyTimerTask</listener-class>
  </listener>
 
</web-app>

 

 

定时发送邮件也就是判断判断时间,功能代码也就不贴了,没什么意思

 

 

最后附上做以上这些东西时在网上搜到的有用的链接,写的不详细的自己以后也可以再看看:

 

java使用定时器,定时发送邮件    http://daidalei321.iteye.com/blog/824691

javamongoDB                    http://wenku.baidu.com/view/9a88930b7cd184254b3535a0.html

记不太清了当时怎么把mongodb安装为服务了....,好像是这篇

MongoDB安装为Windows服务方法与注意事项     http://blog.csdn.net/chaijunkun/article/details/7227967

算了,把搜到的好用的网页都贴上把

mongodb常用命令     http://www.cnblogs.com/cxd4321/archive/2011/06/24/2089051.html

 

 

 

 

 

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值