今天的练习:茉莉QQ机器人监控,线程出错发送邮件提醒

茉莉QQ机器人官网:http://bbs.itpk.cn/forum.php
这是一个php的免费QQ机器人,感觉还不错,可以玩一下!不知道为何用阿里云监控总是出错误,所以随手写了这个。
Git@OSC:https://git.oschina.net/hxgsn/jiankong
发送邮件功能没测试,不知道能不能用!邮箱的代码忘记是哪个大神的了,望大神见谅。。。
邮箱的参数和机器人的URL按自己实际情况修改,谢谢

package com.hxgsn.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import com.hxgsn.util.SendMailDemo;

/**
 * Servlet implementation class jiankong
 */
@WebServlet("/jiankong")
public class jiankong extends HttpServlet implements Runnable {
 private static final long serialVersionUID = 1L;

 static int i;
 static int j;
 static Date time;

 @Override
 public void init() throws ServletException {
  super.init();
  new Thread(new jiankong()).start();
 }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  request.setAttribute("txt", "已经执行了" + i + "次,共失败" + j + "次,上一次执行时间是:" + time);
  request.getRequestDispatcher("/index.jsp").forward(request, response);
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
 }

 @Override
 public void run() {
  SendMailDemo sendMailDemo = new SendMailDemo();
  while (true) {
   System.out.println("定时器启动");
   try {
    i = i + 1;
    System.out.println("开始执行第" + i + "次");
    jk();
    Thread.sleep(60 * 1000);// 休眠,下一次启动时间
   } catch (InterruptedException e) {
    try {
     System.out.println("出现错误,重新执行第" + i + "次");
     jk();
     Thread.sleep(60 * 1000);
    } catch (InterruptedException e1) {
     j = j + 1;
     sendMailDemo.SendMail("出现错误,执行第" + i + "次失败,共失败" + j + "次");
     System.out.println("出现错误,执行第" + i + "次失败");
     e1.printStackTrace();
    }
    e.printStackTrace();
   }
  }
 }

 public void jk() {
  time = new Date();// 记录执行时间
  try {
   Jsoup.connect("http://www.hxgsn.com/webqq/cron.php?hxgsn=1f789c4f").get();// 监控地址
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

}
package com.hxgsn.util;

import java.util.Properties;

public class MailSenderInfo {
 // 发送邮件的服务器的IP(或主机地址)
 private String mailServerHost;
 // 发送邮件的服务器的端口
 private String mailServerPort = "25";
 // 发件人邮箱地址
 private String fromAddress;
 // 收件人邮箱地址
 private String toAddress;
 // 登陆邮件发送服务器的用户名
 private String userName;
 // 登陆邮件发送服务器的密码
 private String password;
 // 是否需要身份验证
 private boolean validate = false;
 // 邮件主题
 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 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;
 }
}
package com.hxgsn.util;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

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);
 }
}
package com.hxgsn.util;

import java.util.Date;

public class SendMailDemo {
 public void SendMail(String txt) {
  // 设置邮件服务器信息
  MailSenderInfo mailInfo = new MailSenderInfo();
  mailInfo.setMailServerHost("smtp.exmail.qq.com");
  mailInfo.setMailServerPort("25");
  mailInfo.setValidate(true);

  // 邮箱用户名
  mailInfo.setUserName("webqq@hxgsn.com");
  // 邮箱密码
  mailInfo.setPassword("test00");
  // 发件人邮箱
  mailInfo.setFromAddress("webqq@hxgsn.com");
  // 收件人邮箱
  mailInfo.setToAddress("121431418@qq.com");
  // 邮件标题
  mailInfo.setSubject("webqq");
  // 邮件内容
  StringBuffer buffer = new StringBuffer();
  buffer.append(new Date() + "\t" + txt);
  mailInfo.setContent(buffer.toString());

  // 发送邮件
  SimpleMailSender sms = new SimpleMailSender();
  // 发送文体格式
  sms.sendTextMail(mailInfo);
  // 发送html格式
  SimpleMailSender.sendHtmlMail(mailInfo);
  System.out.println("邮件发送完毕");
 }
}
package com.hxgsn.util;

import java.util.Date;
import java.util.Properties;
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 boolean sendTextMail(MailSenderInfo mailInfo) {
  // 判断是否需要身份认证
  MyAuthenticator authenticator = null;
  Properties pro = mailInfo.getProperties();
  if (mailInfo.isValidate()) {
   // 如果需要身份认证,则创建一个密码验证器
   authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
  }
  // 根据邮件会话属性和密码验证器构造一个发送邮件的session
  Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
  try {
   // 根据session创建一个邮件消息
   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);
   // 设置邮件消息的主题
   mailMessage.setSubject(mailInfo.getSubject());
   // 设置邮件消息发送的时间
   mailMessage.setSentDate(new Date());
   // 设置邮件消息的主要内容
   String mailContent = mailInfo.getContent();
   mailMessage.setText(mailContent);
   // 发送邮件
   Transport.send(mailMessage);
   return true;
  } catch (MessagingException ex) {
   ex.printStackTrace();
  }
  return false;
 }

 public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
  // 判断是否需要身份认证
  MyAuthenticator authenticator = null;
  Properties pro = mailInfo.getProperties();
  // 如果需要身份认证,则创建一个密码验证器
  if (mailInfo.isValidate()) {
   authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
  }
  // 根据邮件会话属性和密码验证器构造一个发送邮件的session
  Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
  try {
   // 根据session创建一个邮件消息
   Message mailMessage = new MimeMessage(sendMailSession);
   // 创建邮件发送者地址
   Address from = new InternetAddress(mailInfo.getFromAddress());
   // 设置邮件消息的发送者
   mailMessage.setFrom(from);
   // 创建邮件的接收者地址,并设置到邮件消息中
   Address to = new InternetAddress(mailInfo.getToAddress());
   // Message.RecipientType.TO属性表示接收者的类型为TO
   mailMessage.setRecipient(Message.RecipientType.TO, to);
   // 设置邮件消息的主题
   mailMessage.setSubject(mailInfo.getSubject());
   // 设置邮件消息发送的时间
   mailMessage.setSentDate(new Date());
   // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
   Multipart mainPart = new MimeMultipart();
   // 创建一个包含HTML内容的MimeBodyPart
   BodyPart html = new MimeBodyPart();
   // 设置HTML内容
   html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
   mainPart.addBodyPart(html);
   // 将MiniMultipart对象设置为邮件内容
   mailMessage.setContent(mainPart);
   // 发送邮件
   Transport.send(mailMessage);
   return true;
  } catch (MessagingException ex) {
   ex.printStackTrace();
  }
  return false;
 }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Archetype Created Web Application</display-name>
</web-app>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
 <a href="jiankong">查看</a>${txt}
</body>
</html>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.hxgsn</groupId>
 <artifactId>jiankong</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>jiankong Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
  <!-- jdk 版本号 -->
  <jdk.version>1.8</jdk.version>
  <!-- maven 版本号 -->
  <org.apache.maven.plugins.version>3.3</org.apache.maven.plugins.version>
  <!-- junit 版本号 -->
  <junit.version>4.12-beta-3</junit.version>
  <!-- jsoup 版本号 -->
  <org.jsoup.version>1.8.2</org.jsoup.version>
  <!-- mail 版本号 -->
  <javax.mail.version>1.5.0-b01</javax.mail.version>
  <!-- servlet-api 版本号 -->
  <javax.servlet.version>3.1.0</javax.servlet.version>
  <!-- OSChina Maven 镜像地址 -->
  <repository.url>http://maven.oschina.net/content/groups/public/</repository.url>
 </properties>
 <dependencies>
  <!-- junit -->
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>${junit.version}</version>
   <scope>test</scope>
  </dependency>
  <!-- jsoup HTML parser library @ http://jsoup.org/ -->
  <dependency>
   <groupId>org.jsoup</groupId>
   <artifactId>jsoup</artifactId>
   <version>${org.jsoup.version}</version>
  </dependency>
  <!-- mail -->
  <dependency>
   <groupId>javax.mail</groupId>
   <artifactId>mail</artifactId>
   <version>${javax.mail.version}</version>
  </dependency>
  <!-- servlet-api -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>${javax.servlet.version}</version>
   <scope>provided</scope>
  </dependency>
 </dependencies>
 <!-- Maven mirror -->
 <repositories>
  <repository>
   <id>nexus</id>
   <name>local private nexus</name>
   <url>${repository.url}</url>
   <releases>
    <enabled>true</enabled>
   </releases>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </repository>
 </repositories>
 <!-- Maven Plugin mirror -->
 <pluginRepositories>
  <pluginRepository>
   <id>nexus</id>
   <name>local private nexus</name>
   <url>${repository.url}</url>
   <releases>
    <enabled>true</enabled>
   </releases>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </pluginRepository>
 </pluginRepositories>
 <build>
  <finalName>jiankong</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${org.apache.maven.plugins.version}</version>
    <!-- 设置jdk版本 -->
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

分享到: