需求:模拟发生日祝福邮件操作,程序每天 00:00:00 可以查询今天过生日的用户,发送祝福邮件
分析:
A、发邮件通过一个小程序完成 ------ 怎么发邮件
B、程序启动可以执行发邮件程序 ----- 使用监听器实现
C、程序启动执行,以后再次执行应该是次日的 00:00:00,循环操作 ----- 计时器实现
1.导入jar包
mail.jar,standard.jar
2.mail工具类
publicclass MailUtils {
publicstatic void main(String[] args) {
sendMail("455185910@qq.com","22");
}
/**
* 外网邮件发送
* @param to
* @param code
*/
publicstatic void sendMail(String to,String code){
// Session对象:
Propertiesprops = new Properties();
//邮件服务器在本机
//props.setProperty("mail.host","localhost");
//邮件服务器在外网需要用下面两个配置替代
//props.setProperty("mail.smtp.host","smtp.qq.com");
props.setProperty("mail.host","smtp.exmail.qq.com");
//props.setProperty("mail.host","smtp.163.com");
props.setProperty("mail.smtp.auth","true");
Sessionsession = Session.getInstance(props, new Authenticator() {
@Override
publicPasswordAuthentication getPasswordAuthentication() {
//邮件服务器在本机--发件人
// returnnew PasswordAuthentication("server@dachou.com", "123456");
//邮件服务器在外网(QQ有问题!,使用163账户作为发送端没问题,可以给QQ用户发送邮件也是可以的!)
return newPasswordAuthentication("641464521@qq.com","你的密码");
}
});
// Message对象:
Messagemessage = new MimeMessage(session);
// 设置发件人:
try{
message.setFrom(newInternetAddress("641464521@qq.com"));
// 设置收件人:
message.addRecipient(RecipientType.TO,new InternetAddress(to));
// 设置主题:
message.setSubject("来自孙星明的激活邮件");
// 设置内容:
// Stringurl = "http://localhost:8080/store_v1.0/UserServlet?method=active&code="+code;
message.setContent("Hello!张莎莎,好同桌!么么哒!","text/html;charset=UTF-8");
// Transport对象:
Transport.send(message);
}catch (AddressException e) {
e.printStackTrace();
}catch (MessagingException e) {
e.printStackTrace();
}
}
}
3.web.xml中的监听器的配置如下:
<listener>
<listener-class>com.sun.a.web.Listener.EmailListener</listener-class>
</listener>
4.监听器的实现如下:
public classEmailListener implements ServletContextListener {
public voidcontextInitialized(ServletContextEvent sce) {
//查询生日是07-08的用户
//System.out.println("查询指定日期的用户...");
//发送邮件给指定用户!
Timer timer = new Timer();//jdk提供的类
timer.scheduleAtFixedRate(newTimerTask() {
@Override
publicvoid run() {
MailServciemailService = new MailServcie();
try{
List<User> users= mailService.find();
System.out.println(users);
//System.out.println("发送邮件!");
if(users!=null){
for(User user : users) {
MailUtils.sendMail(user.getEmail(), "11");//第二个参数还不需要知道
System.out.println("发给你!");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
}
},DateUtils.getDelayTime(), DateUtils.getOneDay());
}
public voidcontextDestroyed(ServletContextEvent sce) {
}
}
5.emailDao代码如下:
public classEmailDao {
publicList<User> find() throws SQLException {
QueryRunnerqr = new QueryRunner(C3p0Utils.getDataSource());
String sql ="select * from user where birthday like ?";
String str ="%-" + DateUtils.getCurrentMonth() + "-" +DateUtils.getCurrentDay();
Object[]params = {str};
//System.out.println(params[0]);
returnqr.query(sql, new BeanListHandler<User>(User.class), params);
}
}
6.时间工具类
public classDateUtils {
/**
* 获得当前时间距离给定天数零点的毫秒时间
* @param amount
* @return
*/
publicstatic Long getDelayTime(int amount){
//1 设置当前时间
Calendarcalendar = Calendar.getInstance();
DatenewDate = new Date();
calendar.setTime(newDate);
//2 将时分秒设置成0
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
//3 设置指定天数
calendar.add(Calendar.DATE,amount);
//4 计算当前时间距离设置日期零点的延迟时间
returncalendar.getTimeInMillis() - newDate.getTime();
}
/**
* 当前时间具体明天零点的毫秒时间
* @return
*/
public static LonggetDelayTime(){
return getDelayTime(1);
}
/**
* 获得一天的毫秒值
* @return
*/
public static LonggetOneDay(){
return 24 * 60 * 60 *1000L;
}
/**
* 获得几月(两位)
* @return
*/
public static StringgetCurrentMonth(){
//1 设置当前时间
Calendar calendar =Calendar.getInstance();
Date newDate = newDate();
calendar.setTime(newDate);
int m =calendar.get(Calendar.MONTH) + 1;
if(m < 10){
return "0"+ m;
}
return "" +m;
}
/**
* 获得几号(两位)
* @return
*/
public static StringgetCurrentDay(){
//1 设置当前时间
Calendar calendar =Calendar.getInstance();
Date newDate = newDate();
calendar.setTime(newDate);
int d =calendar.get(Calendar.DATE);
if(d < 10){
return "0"+ d;
}
return "" +d;
}
public static voidmain(String[] args) {
// System.out.println(getCurrentMonth());
// System.out.println(getCurrentDay());
System.out.println(getDelayTime()/1000/(60*60));
}
}
7.javaBean类
publicclass User implements Serializable{
/*
* `id`int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`birthday` date DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
*/
privateInteger id;
privateString username;
private Stringbirthday;
private String email;
//setter和getter方法
}
总结:
1、计时器
A、程序中隔某个时间间隔,执行某种操作的需求,是常见的
B、计时器不需要自己编写,一般计算机语言都提供了专门的计时器实现
C、Java 中的计时器实现
1)、一般计时器通过子线程实现
2)、计时器有往复计时器与一次性计时器
3)、计时器使用
2、发邮件
邮件发送是常见操作,但是和 Java 本身关系不大
流程:
环境:
搭建服务器和客户端
3、Java中怎么发邮件?
程序通过代码编写相关实现,一般有现成模板