JAVA 写Excel附件 每天定时发送邮件

本文转载自马前卒 《JAVA 写Excel附件 每天定时发送邮件》
http://hi.baidu.com/star850323/blog/item/63c5750f520e05ec37d1228d.html

本项目需求如下:每天早上8点从数据库查出昨天收入报表,写道Execl中,然后发送到指定邮箱

项目所需要的jar包activation.jar、jxl,jar、mail,jar、msbase.jar、MSSQL-Driver.jar、mssqlserver.jar、msutil.jar、servlet-api.jar

运行方法:启动tomcat,即自动执行。tomcat启动时,会执行一次。所以如果没有技术问题,请勿重启Tomcat,因为每次重启都会发送一封邮件。

1、写一个Servlet,用于实现每天早上8点定时执行发送邮件的任务:

package com.email;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendMailServlet extends HttpServlet{
    private Timer timer;
    private SendMailTask tt;
public SendMailServlet() {
   super();
}

public void destroy() {
   super.destroy();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
   out.println("<HTML>");
   out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
   out.println(" <BODY>");
   out.print("    This is ");
   out.print(this.getClass());
   out.println(", using the POST method");
   out.println(" </BODY>");
   out.println("</HTML>");
   out.flush();
   out.close();
}

public void init() throws ServletException {
   Thread t = new Thread(){
    public void run(){
     timer = new Timer();
     tt = new SendMailTask();
     Calendar cal = new GregorianCalendar(2010, 0, 8, 0, 0, 0);// 从2010年1月8号8点开始执行
          Date date = cal.getTime();
     timer.schedule(tt, date, 24*60*60*1000);//8点后,每24小时执行一次
    }  
   };
   t.start();  
}
}

2、在web.xml中加入如下配置

<servlet>
    <servlet-name>SendMailServlet</servlet-name><!--邮件发送程序-->
    <servlet-class>com.email.SendMailServlet</servlet-class><!--servlet所在类-->
      <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
   <servlet-name>SendMailServlet</servlet-name><!--名字自取,但必须与servlet一样-->
   <url-pattern>/SendMailServlet</url-pattern>
</servlet-mapping>

3、servlet调用的任务类

package com.email;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.TimerTask;
import com.dao.*;

public class SendMailTask extends TimerTask   
{  
   public static long runTime = 1;  
   public SendMailTask()  
   {  
   }
  
   public void run()   
   {  
    java.util.Date   today=new   java.util.Date();
   today.setTime(today.getTime());
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     String startdate = formatter.format(today);      
     String day = String.valueOf(Integer.parseInt(startdate.substring(8,10))-1);
     if(day.length()==1)
     startdate = startdate.substring(0,8)+"0"+day+" 00:00:00";
     else
     startdate = startdate.substring(0,8)+"0"+day+" 00:00:00";
     String date = startdate.substring(0,4)+startdate.substring(5,7)+startdate.substring(8,10);
    try {
     IncomeReport.statData();//生成EXCEL报表
    } catch (IOException e1) {
     e1.printStackTrace();
    } catch (SQLException e1) {
     e1.printStackTrace();
    }
    if(runTime>=100)  
     runTime = 0;  
     String host = "smtp.qq.com";
   String user = "[email protected]";  
   String password = "123456";  
   String subject = "XX收入日报表";
   String[] to = {"[email protected]","[email protected]"};
   String from = "[email protected]";  
   String bodyashtml = "请查看附件(收入日报表)!";
   String attachfile = "E:\\projects\\tmp\\"+date+"_income.xls";//附件生成位置
    try {
    SendMail send = new SendMail();
    send
    .setHost(host);
    send.setUser(user);
    send.setPass(password);
    send.setSubject(subject);
    send.setFrom(from);
    send.setBodyAsHTML(bodyashtml);//以HTML形式存放内容
    send.addAttachFromFile(attachfile,""+date+"_income.xls");//附件路径,附件名称
    for(int i=0;i<to.length;i++){
     send.setTo(to[i]);
     send.send();
    }
    System.out.println(date+"邮件发送成功!");
   } catch (Exception e) {
    e.printStackTrace();
   }
   }  
}
4、发送邮件的程序

package com.email;
/**
* @author 527251717
* SendMail.java
*/
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


public class SendMail {
        public static String TEXT = "text/plain;charset=gb2312";
        public static String HTML = "text/html;charset=gb2312";
        private String host; //邮件服务器
        private String user; //用户名
        private String pass;//用户密码
        private String from;//发信人
        private String to;//收信人
        private String cc;//Carbon Copy, 抄送邮件给某人
        private String bc;//bcc Blind Carbon Copy,隐蔽副本 隐蔽抄送给某人
        private String subject;//邮件主题
        private BodyPart body;//邮件内容
        private boolean needAuth; //是否需要认证
        private List attaches;//邮件附件
/**
* 构造方法
*
*/
        public SendMail() {
                needAuth = true;
                attaches = new ArrayList();
        }
        /**
         * 构造方法
         * @param host
         */
        public SendMail(String host) {
                needAuth = true;
                attaches = new ArrayList();
                this.host = host;
        }
        /**
         * 构造方法
         * @param host
         * @param user
         * @param pass
         */
        public SendMail(String host, String user, String pass) {
                needAuth = true;
                attaches = new ArrayList();
                this.host = host;
                this.user = user;
                this.pass = pass;
        }
//设置邮件服务器是否需要认证
        public void setNeedAuth(boolean needAuth) {
                this.needAuth = needAuth;
        }
        public void setFrom(String from) {
                this.from = from;
        }
        public void setTo(String to) {
                this.to = to;
        }
        public String getPass() {
                return pass;
        }
        public String getUser() {
                return user;
        }
        public void setPass(String string) {
                pass = string;
        }
        public void setUser(String string) {
                user = string;
        }

        public String getFrom() {
                return from;
        }
        public String getHost() {
                return host;
        }
        public boolean isNeedAuth() {
                return needAuth;
        }
        public String getSubject() {
                return subject;
        }
        public void setHost(String string) {
                host = string;
        }
        public void setBlindTo(String bc) {
                this.bc = bc;
        }
        public void setCopyTo(String cc) {
                this.cc = cc;
        }
        public void setSubject(String subject) {
                this.subject = subject;
        }
/**
* 设置邮件内容的形式
* @param string
* @param contentType
*/
        public void setBody(String string, String contentType) {
                try {
                        body = new MimeBodyPart();
                        DataHandler dh = new DataHandler(string, contentType);
                        body.setDataHandler(dh);
                } catch (Exception exception) {
                }
        }
/**
* 设置邮件的内容的格式为文本格式
* @param string
*/
        public void setBodyAsText(String string) {
                setBody(string, TEXT);
        }
/**
* 以HTMl的形式存放内容
* @param string
*/
        public void setBodyAsHTML(String string) {
                setBody(string, HTML);
        }
/**
* 从文件中自动导入邮件内容
* @param filename
*/
        public void setBodyFromFile(String filename) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(filename);
                        DataHandler dh = new DataHandler(fds);
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* 从一个URL导入邮件的内容
* @param url
*/
        public void setBodyFromUrl(String url) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        URLDataSource ur = new URLDataSource(new URL(url));
                        DataHandler dh = new DataHandler(ur);
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* 将String中的内容存放入文件showname,并将这个文件作为附件发送给收件人
* @param string 为邮件的内容
* @param showname 显示的文件的名字
*/
        public void addAttachFromString(String string, String showname) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        DataHandler dh = new DataHandler(string, TEXT);
                        mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null));
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* filename为邮件附件
*在收信人的地方以showname这个文件名来显示
* @param filename
* @param showname
*/
        public void addAttachFromFile(String filename, String showname) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(filename);
                        DataHandler dh = new DataHandler(fds);
                        mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null));
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* 将互联网上的一个文件作为附件发送给收信人
* 并在收信人处显示文件的名字为showname
* @param url
* @param showname
*/
        public void addAttachFromUrl(String url, String showname) {
                try {
                        BodyPart mdp = new MimeBodyPart();
                        URLDataSource ur = new URLDataSource(new URL(url));
                        DataHandler dh = new DataHandler(ur);
                        mdp.setFileName(MimeUtility.encodeWord(showname, "gb2312", null));
                        mdp.setDataHandler(dh);
                        attaches.add(mdp);
                } catch (Exception exception) {
                }
        }
/**
* 发送邮件,需要身份认证
* @throws Exception
*/
        public void send() throws Exception {
                try {
                   Properties props = new Properties();
                        if (host != null && !host.trim().equals(""))
                                props.setProperty("mail.smtp.host", host);//key   value
                        else
                                throw new Exception("没有指定发送邮件服务器");
                        if (needAuth)
                                props.setProperty("mail.smtp.auth", "true");
                        Session s = Session.getInstance(props, null);
                        MimeMessage msg = new MimeMessage(s);
                        //设置邮件主题
                        msg.setSubject(subject);
                        //设置邮件发送时间
                        msg.setSentDate(new Date());
                        //指定发件人
                        if (from != null)
                                msg.addFrom(InternetAddress.parse(from));
                        else
                                throw new Exception("没有指定发件人");
                        //指定收件人
                        if (to != null)
                                msg.addRecipients(javax.mail.Message.RecipientType.TO,InternetAddress.parse(to));
                        else
                                throw new Exception("没有指定收件人地址");
                        //指定抄送
                        if (cc != null)
                                msg.addRecipients(javax.mail.Message.RecipientType.CC,InternetAddress.parse(cc));
                        //指定密送
                        if (bc != null)
                                msg.addRecipients(javax.mail.Message.RecipientType.BCC,InternetAddress.parse(bc));
                        Multipart mm = new MimeMultipart();
                        //设置邮件的附件
                        if (body != null)
                                mm.addBodyPart(body);
                        for (int i = 0; i < attaches.size(); i++) {
                                BodyPart part = (BodyPart) attaches.get(i);
                                mm.addBodyPart(part);
                        }
//    设置邮件的内容
                        msg.setContent(mm);
                        //保存所有改变
                        msg.saveChanges();
                        //发送邮件服务器(SMTP),简单邮件传输协议
                        Transport transport = s.getTransport("smtp");
                        //访问邮件服务器
                        transport.connect(host, user, pass);
                        //发送信息
                        transport.sendMessage(msg, msg.getAllRecipients());
                        //关闭邮件传输
                        transport.close();
                } catch (Exception e) {
                   e.printStackTrace();
                        throw new Exception("发送邮件失败:", e);
                }
        }
}
5、连接数据库的程序,数据库用的是SQL SERVER

package com.dao;

import java.sql.*;

public final class DBConnection {

Statement stmt = null;
ResultSet rs = null;
public DBConnection() {}

public static Connection getConnection()
{
        Connection con=null;
        String driver="net.sourceforge.jtds.jdbc.Driver";
        String url="jdbc:jtds:sqlserver://localhost:端口/数据库名"; //数据库端口根据自己的实际情况填写
        String user="sa";
        String password="密码";
    try
    {
    Class.forName(driver).newInstance();
    con=DriverManager.getConnection(url,user,password);
    }
    catch(Exception e)
    {
       e.printStackTrace();
    }
    return con;
}

/**
   * 关闭连接
   * @param conn
   */
   public static void close(Connection conn){
       try{
           if(conn!=null)
           conn.close();
           conn = null;
       }catch(SQLException e){
           //
       }
   }

   /**
    * 关闭Statement
    * @param stmt
    */
   public static void close(Statement stmt){
       try{
           if(stmt!=null)
           stmt.close();
           stmt = null;
       }catch(SQLException e){
           //
       }
   }

   /**
    * 关闭ResultSet
    * @param rs
    */
   public static void close(ResultSet rs){
       try{
           if(rs!=null)
           rs.close();
           rs = null;
       }catch(SQLException e){
           //
       }
   }
}
6、将数据库查询的数据写入Excel中

package com.dao;

import java.io.*;
import java.sql.*;
import java.text.*;

import javax.servlet.ServletException;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class IncomeReport {
public static void statData() throws IOException, SQLException{
   java.util.Date   today=new   java.util.Date();
   today.setTime(today.getTime());
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     String startdate = formatter.format(today);      
     String day = String.valueOf(Integer.parseInt(startdate.substring(8,10))-1);
     if(day.length()==1)
     startdate = startdate.substring(0,8)+"0"+day+" 00:00:00";
     else
     startdate = startdate.substring(0,8)+"0"+day+" 00:00:00";
     String date = startdate.substring(0,4)+startdate.substring(5,7)+startdate.substring(8,10);
   Connection conn = null;
   Statement stmt = null;
   ResultSet rs = null;
   String sql = "select a1,a2,a3,a4 from 数据库名";
   sql += " where Date between '"+startdate+"' and '"+startdate+"'";//根据自己数据库实际情况选择时间
   OutputStream os = new FileOutputStream("E:\\projects\\tmp\\"+date+"_income.xls");//文件所在位置
   WritableWorkbook wwb = Workbook.createWorkbook(os); //创建Excel工作表 指定名称和位置
        WritableSheet ws = wwb.createSheet("XX收入日报表",0);//创建一个sheet
        WritableFont wf = new WritableFont(WritableFont.TIMES, 8, WritableFont.NO_BOLD, false);
        WritableCellFormat wcfF = new WritableCellFormat(wf);
   try {
     conn = DBConnection.getConnection();
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql);
      writeExcel(rs,wwb,ws,wcfF);
   } catch (Exception ex) {
      ex.printStackTrace();
   } finally {
    DBConnection.close(rs);
      DBConnection.close(stmt);
   }
}

public static void writeExcel(ResultSet rs,WritableWorkbook wwb,
            WritableSheet ws,WritableCellFormat wcfF) throws ServletException
     {
     String[] title = {"a1","a2",“a3","a4"};
        try
        {
         int i = 0;
         Label label = null;
         for(int k=0;k<4;k++){
          label = new Label(k,i,title[k],wcfF);
          ws.addCell(label);
         }
         i++;
            //**************往工作表中添加数据*****************//
            while(rs.next()){//行
               for(int j=0;j<4;j++){//列
                if(j>1)
                 label = new Label(j,i,rs.getString(j+1)+"%",wcfF);
                else
                 label = new Label(j,i,rs.getString(j+1),wcfF);
                ws.addCell(label);
               }
               i++;
            }
            //写入工作表
            wwb.write();
            wwb.close();
        }
        catch(Exception e)
        {
            throw new ServletException(e);
        }
     }
}

7、转换中文

package com.tool;

public class ToChinese{
    public ToChinese() {}
    public String getGB2312(String s){
     if (s != null && !"".equals(s)) {
    try {
     s = new String(s.getBytes("8859_1"), "gb2312");
     return s;
    } catch (Exception ex) {
     System.out.print(ex.getMessage());
    }
   }
   return "";
    }
}

你可能感兴趣的:(JAVA 写Excel附件 每天定时发送邮件)