java定时发送邮件

java定时发送邮件默认分类 2008-11-13 16:17:43 阅读615 评论2   字号:大中小 订阅 .

测试时用的是tomcat6.0服务器:服务器一起,就会自动加载web.xml中的内容,进行时间判断,定时发送;

扩展:可以在中间加上对数据库的操作

1.先导入两个jar.包

mail.jar、activation.jar

2.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

  <servlet>
    <servlet-name>mailsenderservlet</servlet-name><!--邮件发送程序-->
   
    <servlet-class>com.email.MailSenderServlet</servlet-class>
   
    <init-param>
      <param-name>server</param-name><!--邮件服务器SMTP地址-->
      <param-value>smtp.163.com</param-value>
    </init-param>
   
    <init-param>
      <param-name>port</param-name><!--邮件服务器SMTP端口-->
      <param-value>25</param-value>
    </init-param>
   
    <init-param>
      <param-name>address</param-name><!--邮件地址-->
      <param-value>[email protected]</param-value>
    </init-param>
   
    <init-param>
      <param-name>username</param-name><!--邮件账号-->
      <param-value>username</param-value>
    </init-param>
   
    <init-param>
      <param-name>password</param-name><!--密码-->
      <param-value>******</param-value>
    </init-param>
   
    <init-param>
      <param-name>validate</param-name><!--SMTP服务器是否要求验证-->
      <param-value>true</param-value>
    </init-param>
   
    <init-param>
      <param-name>time</param-name><!--扫描数据库时间间隔(分钟)-->
      <param-value>1</param-value>
    </init-param>
   
    <load-on-startup>1</load-on-startup>
   
  </servlet>
 
   <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>


3.定义两个类MailSenderServlet.java、MailSender.java

MailSenderServlet.java要依赖MailSender.java



MailSenderServlet.java

package com.email;

import java.io.File;

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

public class MailSenderServlet extends HttpServlet {

private static final long serialVersionUID = 4114629936094514228L;

private MailSender sender;
private Thread t;

public void init() throws ServletException {
 
  System.out.println("auto Send Mial***********begin") ;
 
  sender = new MailSender();
  //sender.setRoot(root);
 
  sender.setRoot(new File("D:/work2/auto_send_mail/"));
 
  String server = getInitParameter("server");
 
  String port = getInitParameter("port");
 
  String address = getInitParameter("address");
 
  String username = getInitParameter("username");
 
  String password = getInitParameter("password");
 
  if (server == null || port == null || address == null || username == null || password == null) {
  
   System.out.println("系统文件web.xml错误:邮件发送程序初始化失败!");
   return;
  }
 
  sender.setServer(server);
 
  sender.setPort(port);
 
  sender.setAddress(address);
 
  sender.setUsername(username);
 
  sender.setPassword(password);

  String time = getInitParameter("time");
 
  if (time != null) {
  
   sender.setTime(Integer.parseInt(time));
  }
 
  String validate = getInitParameter("validate");
 
  if (validate != null) {
  
   sender.setValidate(Boolean.valueOf(validate).booleanValue());
  }
 
  System.out.println("auto Send Mial***********parameter :"+"server ="+server+" port ="+port+" address ="+address+" username ="+username+" password ="+password+" time ="+time+" validate ="+validate) ;
 
  t = new Thread(sender);
 
  //启动邮件发送线程
  t.start();
 
}

public void destroy() {
 
  sender.stop(); //停止邮件发送线程
 
  try {
   
   t.join(1000);
  
   if (t.isAlive()) {
   
    System.out.println("邮件发送线程未停止。");
   }
  







MailSender.java



package com.email;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;
import javax.activation.*;
import javax.mail.*;
import javax.mail.Message.*;
import javax.mail.internet.*;

public class MailSender implements Runnable {

private int time = 5 * 60 * 1000; //扫描数据库时间间隔

private boolean flag = true; //停止线程标记

private String server = "127.0.0.1"; //SMTP服务器地址

//add
private static final String smtp_host = "mailserver";//邮件服务器名:要改

private String port = "25"; //SMTP服务器端口

private String address; //用于发送EMAIL的发送者地址

private String username; //发送者的用户名

private String password; //发送者的密码

private boolean validate = true; //邮件服务器是否要求验证

private File root = null; //WEB根目录

//MailConfigManager manager = MailConfigManager.getInstance();

public MailSender() {
 
  System.out.println("auto Send Mial***********MailSender") ;
}

public File getRoot() {
  return root;
}

public void setRoot(File root) {
  this.root = root;
}

public void setAddress(String address) {
  this.address = address;
}

public void setPassword(String password) {
  this.password = password;
}

public void setPort(String port) {
  if (port != null && port.length() > 0) {
   this.port = port;
  }
}

public void setServer(String server) {
  this.server = server;
}

public void setUsername(String username) {
  this.username = username;
}

public void setValidate(boolean validate) {
  this.validate = validate;
}

public void setTime(int minute) {
  this.time = minute * 60 * 1000;
}


public void run() {
 
  System.out.println("auto Send Mial***********run") ;
  //保存前一次发送邮件的时间
  long lastTime = new Date().getTime();
  System.out.println("auto Send Mial***********lastTime ="+lastTime) ;
 
  System.out.println("auto Send Mial***********k ="+(new Date().getTime() - lastTime)) ;
 
  System.out.println("auto Send Mial***********time ="+time) ;
 
  //服务器停止时退出线程
  while (flag) {
  
   long k = new Date().getTime() - lastTime;
  
   //防止系统修改时间
   if (k < -1000) {
   
    lastTime = new Date().getTime();
    continue;
   }
  
   //超过设定时间间隔开始发送邮件
   if (k > time) {
   
    System.out.println("auto Send Mial***********k > time") ;
    try {
     send(
       "小样", "<html> <FONT color=\"red\">您有新签核,请登录" +

       "<a href=http://localhost:1111/mold/form/login.jsp>" +

       "模具系统</a>查看</FONT><P></P>" +

       "<FONT color=\"#666666\" size=\"2\">来自系统自动发送邮件,请勿回复!</FONT></html>"
     );
    } catch (Exception e) {
    
     e.printStackTrace();
    }
   
    //sendData();
    lastTime = new Date().getTime();
   }
  
   try {
   
    Thread.sleep(100);
   
   } catch (Exception e) {
   
   }
  }
}

public void stop() {
 
  flag = false;
}

/**
  * 检索数据库,并发送邮件
  */
private void sendData() {
 
  System.out.println("auto Send Mial***********sendData") ;
 
  //读取数据库数据
  ResultSet rs = null;

  try {
  
   Session session = Session.getInstance(getProperties(),new Authentic());
  
   //服务器停止时退出线程
   while (flag) {
  
    //发送地址(从rs中得到)
    String toAddress = null;
    //邮件主题
    String subject = null;
    //邮件内容
    String content = null;
    //所有附件(绝对路径)
    String file[] = null;

    //发送邮件
    sendMail(session, toAddress, subject, content, file);
   }
  } catch (Exception e) {
  
   e.printStackTrace();
  } finally {
  
   if (rs != null) {
   
    try {
    
     rs.close();
    
    } catch (SQLException e) {
    
    }
   }
  }
}

/**
  * 发送邮件
  * @param session 会话
  * @param toAddress 目的地址
  * @param subject 邮件主题
  * @param content 邮件内容(HTML)
  * @param files 邮件附件
  * @return 是否发送成功
  */
private boolean sendMail(Session session, String toAddress, String subject,String content, String[] files) {

  toAddress = "收件人地址";

  try {
  
   Message rs = new MimeMessage(session);
  
   Address from = new InternetAddress(address);
  
   //发送地址
   rs.setFrom(from);
  
   //接收地址
   rs.setRecipient(RecipientType.TO, new InternetAddress(toAddress));
  
   //邮件主题
   rs.setSubject(subject);
  
   Multipart mp = new MimeMultipart();
  
   BodyPart html = new MimeBodyPart();
  
   //邮件HTML内容
   html.setContent(content, "text/html; charset=GBK");
  
   mp.addBodyPart(html);
  
   //邮件附件
   if (files != null && files.length > 0) {
   
    for (int i = 0; i < files.length; i++) {
    
     MimeBodyPart mbp = new MimeBodyPart();
    
     FileDataSource fds = new FileDataSource(files[i]);
    
     mbp.setDataHandler(new DataHandler(fds));
    
     mbp.setFileName(MimeUtility.encodeWord(files[i], "GBK",null));
    
     mp.addBodyPart(mbp);
    }
   }
  
   //邮件全部内容
   rs.setContent(mp);
  
   //发送时间
   rs.setSentDate(new Date());
  
   //发送
   Transport.send(rs);
  
   return true;
  
  } catch (Exception e) {
  
   e.printStackTrace();
  
   return false;
  
  }
}

/**
  * 邮件会话属性
  * @return 会话属性
  */
private Properties getProperties() {
 
  Properties rs = new Properties();
 
  rs.put("mail.smtp.host", server);
 
  rs.put("mail.smtp.port", port);
 
  rs.put("mail.smtp.auth", validate ? "true" : "false");
 
  return rs;
 
}

//验证密码
class Authentic extends Authenticator {

  public Authentic() {
  
  }

  public PasswordAuthentication getPasswordAuthentication() {
  
   return new PasswordAuthentication(username, password);
  }

}




public static void send(String subject, String text) throws Exception {
 
  Properties props = new Properties();
 
  props.put("mail.smtp.host", smtp_host);
 
  Session session = Session.getDefaultInstance(props, null);
 
  MimeMessage message = new MimeMessage(session);
 
  try {
  
    message.setFrom(new InternetAddress("Mold_System"));//添加发件人
   
    InternetAddress[] address = { new InternetAddress("address") };//定义收件人地址:要改
   
    message.addRecipients(Message.RecipientType.TO, address);//添加收件人
   
    message.setSubject(subject);//添加主题
   
    message.setText(text);//添加内容
   
    Transport.send(message);//发送信息
   
   } catch (Exception e) {
   
    throw e;
   }
}


}

  } catch (Exception e) {
  
  }
}

}

你可能感兴趣的:(java,xml,Web,servlet,SQL Server)