在看完本随笔仍然不理解的可以看  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收到邮件

最新文章

  1. PHP基础知识之变量
  2. 5-06使用Sql 语句为表添加约束
  3. memcached学习笔记1--概念
  4. Asp.net MVC2中你必须知道的扩展点(一):Controller Factory
  5. Collision使用 获取其组件执行变色操作
  6. [转载]Linux的时间与时钟中断处理
  7. elk 架构
  8. C#网络编程系列(两)它Socket同步TCPserver
  9. sublime text3编译运行C,Java程序的一些配置
  10. 创建一个servlet
  11. (2)Deep Learning之线性单元和梯度下降
  12. Struts2 配置文件小结
  13. [Codeforces 864D]Make a Permutation!
  14. thrift实现HDFS文件操作
  15. Java EE ----- Container/Injection
  16. Winscp无法连接linux虚拟机解决
  17. eclipse 工作区空格和回车键显示为乱码
  18. Java NIO6:选择器1——理论篇
  19. Flex学习笔记,脚本式验证
  20. jdbc mysql driver 6.0.2

热门文章

  1. Base-64编码介绍
  2. 不要用for循环去遍历LinkedList
  3. Python基础篇(四)
  4. Xposed快速hook关键点
  5. flex 布局 input 宽度不自适应
  6. 树莓派3B上部署运行.net core 2程序
  7. QT使用painter绘制文字时的居中显示
  8. 【Tools】ubuntu16.04升级Python2.7到3.5
  9. 搭建简易的c语言与python语言CGI和Apache服务器的开发环境
  10. 自动化测试工具selenium的使用