javaWeb之自動發送郵件生日祝福(ServletContextListener監聽)


在看完本隨筆仍然不理解的可以看  javaWeb郵箱發送  :里面有具體的郵箱服務器配置

 

企業在員工生日當天發送郵箱生日祝福:

  一般是用監聽器完成:  而合適的監聽是ServletContextListener   ,每天都定時查看該天過生日的員工,並發送郵件祝福

創建一個監聽器:

package com.study.mail;
import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.study.utils.DataSourceUtils; public class MyServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent arg0) { Timer timer=new Timer(); final SimpleDateFormat sdf=new SimpleDateFormat("MM-dd"); final QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource()); timer.schedule(new TimerTask() { @Override public void run() { //判斷今天的日期 String today="\"%"+sdf.format(new Date())+"%\""; // today 容易寫成 "%"+sdf.format(new Date())+"%" // 導致生成的sql語句為: select * from user where birthday like %11-13% // 正常運行的sql語句為: select * from user where birthday like "%11-13%", //因此使用 ‘\’ 轉義符把 " 轉化 //今天生日的員工 String sql="select * from user where birthday like "+today; List<User> userList =null; try { System.out.println(sql); userList = qr.query(sql, new BeanListHandler<User>(User.class)); } catch (SQLException e) { e.printStackTrace(); } if (userList!=null) { for (User user : userList) { String emailMsg="親愛的"+user.getName()+"<br/>祝你生日快樂"; try { MailUtils.sendMail(user.getEmail(), "生日祝福", emailMsg); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } } } }, new Date(), 1000*5); //new Date() 具體的項目不為這個, 1000*5 // 真正項目是1000*60*60*24 一天 } public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } }

User  類:

package com.study.mail;

public class User {
    
    private String name;
    private String passWord;
    private String email;
    private String birthday;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getBirthday() {
        return birthday;
    }
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
    
    
}

 

MailUtils類:

package com.study.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {

    public static void sendMail(String email,String subject, String emailMsg)
            throws AddressException, MessagingException {
        // 1.創建一個程序與郵件服務器會話對象 Session
        
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "SMTP");//發送郵件的協議
        props.setProperty("mail.host", "localhost");//發送郵件的服務器地址
        props.setProperty("mail.smtp.auth", "true");// 指定驗證為true

        // 創建驗證器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("tom", "123456");//發送郵件的賬號認證
            }
        };

        Session session = Session.getInstance(props, auth);

        // 2.創建一個Message,它相當於是郵件內容
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress("tom@study.com")); // 設置發送者

        message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 設置發送方式與接收者

        message.setSubject(subject);//設置郵件的主題
        // message.setText("這是一封激活郵件,請<a href='#'>點擊</a>");
        //設置郵件的內容
        message.setContent(emailMsg, "text/html;charset=utf-8");
        
        // 3.創建 Transport用於將郵件發送

        Transport.send(message);
    }
}

 

DataSourceUtils類

package com.study.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {

    private static DataSource dataSource = new ComboPooledDataSource();

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    // 直接可以獲取一個連接池
    public static DataSource getDataSource() {
        return dataSource;
    }
    
    public static Connection getConnection() throws SQLException{
        return dataSource.getConnection();
    }

    // 獲取連接對象
    public static Connection getCurrentConnection() throws SQLException {

        Connection con = tl.get();
        if (con == null) {
            con = dataSource.getConnection();
            tl.set(con);
        }
        return con;
    }

    // 開啟事務
    public static void startTransaction() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.setAutoCommit(false);
        }
    }

    // 事務回滾
    public static void rollback() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.rollback();
        }
    }

    // 提交並且 關閉資源及從ThreadLocall中釋放
    public static void commitAndRelease() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.commit(); // 事務提交
            con.close();// 關閉資源
            tl.remove();// 從線程綁定中移除
        }
    }

    // 關閉資源方法
    public static void closeConnection() throws SQLException {
        Connection con = getCurrentConnection();
        if (con != null) {
            con.close();
        }
    }

    public static void closeStatement(Statement st) throws SQLException {
        if (st != null) {
            st.close();
        }
    }

    public static void closeResultSet(ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
    }

}

C3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///WEBListener</property>
    </default-config> 
</c3p0-config> 

mysql數據庫:

 

 

foxmail用戶

應用開啟:生日當天的user收到郵件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM