订時執行任務後自動發送郵件
----------------------------1: 時間管理,到點自動開始------------------------
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Timer;
public class TimerManager {
private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
private static final String CONFIG_FILE_PATH = "C:\\task.ini";
/*
task.ini 格式必須是
key=value
*/
public TimerManager() {
try{
Calendar calendar = Calendar.getInstance();
// 設置每日執行的時間
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(getConfig("DAYENDHOUR")));
calendar.set(Calendar.MINUTE, Integer.parseInt(getConfig("DAYENDMINUTE")));
Date date = calendar.getTime();
/**
* 如果更新系統的時間在設置時間之前,
* 則此任務會自動執行一次,數據會有問題!
* 所以這裏要加一天,就是說在明天的這個時候再執行
*/
if (date.before(new Date())) {
date = this.addDay(date, 1);
}
Timer timer = new Timer();
//調用我們已經寫好的任務
ScheduleDataTimerTask task = new ScheduleDataTimerTask();
timer.schedule(task, date, PERIOD_DAY);
}catch( Exception e){
e.printStackTrace();
}
}
public Date addDay(Date date, int num) {
Calendar startDT = Calendar.getInstance();
startDT.setTime(date);
startDT.add(Calendar.DAY_OF_MONTH, num);
return startDT.getTime();
}
public static void readFileForDayend() throws Exception {
File file = new File(CONFIG_FILE_PATH);
Properties properties = new Properties();
try {
FileInputStream fi = new FileInputStream(CONFIG_FILE_PATH);
properties.load(fi);
Enumeration emu = properties.keys();
while (emu.hasMoreElements()) {
String theKey = (String) emu.nextElement();
String theValue = properties.getProperty(theKey);
System.setProperty(theKey, theValue);
}
try {
fi.close();
fi = null;
} catch (Exception E) {
}
} catch (FileNotFoundException e) {
throw new Exception(" file not found. "
+ file.getAbsolutePath());
}
}
public static String getConfig(String parameterName) throws Exception
{
String propValue = System.getProperty(parameterName);
File file = new File(CONFIG_FILE_PATH);
if (!file.isFile())
{
throw new Exception(" file not found." + file.getAbsolutePath());
}
if (propValue == null)
{
readFileForDayend();
propValue = System.getProperty(parameterName);
}
if (propValue == null)
{
throw new Exception("Parameter '" + parameterName + "' not found");
}else{
return propValue;
}
}
}
-----------------------------------2: 監聽類, ----------------------------------------
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ScheduleActionListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent envt) {
TimerManager time = new TimerManager();
}
public void contextDestroyed(ServletContextEvent envt) {}
}
web.xml需要配置:
<listener>
<listener-class>
ScheduleActionListener
</listener-class>
</listener>
-----------------------------------3: 要執行的任務---------------------------------------
import java.util.TimerTask;
public class ScheduleDataTimerTask extends TimerTask {
public void run() {
System.out.println("---------------------自動執行開始---------------------");
}
-----------------------------------4: 發送郵件類--------------------------------------------
import java.util.Date;
import java.util.StringTokenizer;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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;
public class SimpleMailSender {
// 發送帶抄送的郵件
public static boolean sendMailtoMultiCC(MailSenderInfo mailInfo){
MyAuthenticator authenticator = null;
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(),
mailInfo.getPassword());
}
Session sendMailSession = Session.getInstance(mailInfo
.getProperties(), authenticator);
try {
Message mailMessage = new MimeMessage(sendMailSession);
Address from = new InternetAddress(mailInfo.getFromAddress());
mailMessage.setFrom(from);
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO, to);
if(!"".equals(mailInfo.getToAddressCCs()) && null!=mailInfo.getToAddressCCs()){
//JDK1.3沒有split函數,無奈只能用StringTokenizer
StringTokenizer st = new StringTokenizer(mailInfo.getToAddressCCs(),",");
if (st.countTokens()!=0){
Address[] ccAdresses = new InternetAddress[st.countTokens()];
int i =0;
while(st.hasMoreTokens()){
ccAdresses[i] = new InternetAddress(st.nextToken());
i++;
}
mailMessage.setRecipients(Message.RecipientType.CC, ccAdresses);
}
}
mailMessage.setSubject(mailInfo.getSubject());
mailMessage.setSentDate(new Date());
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
public boolean sendMail(
boolean isFromConfig, //是否從配置文件讀, true: 是, false: 否
String serverHost,
String serverPort,
boolean isValidate, //是否需要驗證, true: 是, false: 否
String userName,
String passWord,
String fromAddress,
String toAddress,
String toAddressCCS, // 抄送的郵箱地址
String subJect,
String content
) {
boolean flag=false;
MailSenderInfo mailInfo = new MailSenderInfo();
// 從配置文件讀
try{
if(isFromConfig){
mailInfo.setMailServerHost(ReadConfig.getConfig("SERVERHOST"));
mailInfo.setMailServerPort(ReadConfig.getConfig("SERVERPORT"));
mailInfo.setValidate(ReadConfig.getConfig("ISVALIDATE").trim().toUpperCase().equals("TRUE"));
mailInfo.setUserName(ReadConfig.getConfig("USERNAME"));
mailInfo.setPassword(ReadConfig.getConfig("PASSWORD"));
mailInfo.setFromAddress(ReadConfig.getConfig("FROMADDRESS"));
mailInfo.setToAddress(ReadConfig.getConfig("TOADDRESS"));
mailInfo.setToAddressCCs(ReadConfig.getConfig("TOADDRESSCCS"));
// 手動設置
}else{
mailInfo.setMailServerHost(serverHost);
mailInfo.setMailServerPort(serverPort);
mailInfo.setValidate(isValidate);
mailInfo.setUserName(userName);
mailInfo.setPassword(passWord);
mailInfo.setFromAddress(fromAddress);
mailInfo.setToAddress(toAddress);
mailInfo.setToAddressCCs(toAddressCCS);
}
}catch(Exception e){
e.printStackTrace();
flag=false;
}
//郵件主題和內容經常變動, 所以允許自己手動填寫
mailInfo.setSubject(subJect);
mailInfo.setContent(content);
if(SimpleMailSender.sendMailtoMultiCC(mailInfo)){
flag=true;
}
return flag;
}
}
-----------------------------------------5: 郵箱驗證------------------------------------
import javax.mail.*;
public class MyAuthenticator extends Authenticator{
String userName=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
----------------------------------------6: 郵箱基本信息---------------------------------------
import java.util.Properties;
public class MailSenderInfo {
private String mailServerHost;
private String mailServerPort;
private String fromAddress;
private String toAddress;
private String toAddressCCs;
private String userName;
private String password;
private boolean validate;
private String subject;
private String content;
private String[] attachFileNames;
public Properties getProperties() {
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getToAddressCCs() {
return toAddressCCs;
}
public void setToAddressCCs(String toAddressCCs) {
this.toAddressCCs = toAddressCCs;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
}