码迷,mamicode.com
首页 > 其他好文 > 详细

服务器接口状态监控,异常报警到电子邮箱。

时间:2016-06-21 08:02:09      阅读:367      评论:0      收藏:0      [点我收藏+]

标签:

使用HTTP URL,发送请求并接收服务器接口响应消息,如5分钟内发生5次异常,则把异常信息发送到指定电子邮箱中;指定时间内异常未达到5次则清零。

1,Http Post

package m;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

import MailSenderInfo.MyAuthenticator;

public class test_postout {
	static String sessionId = "";
	static int num;
	static int j;
	// 默认的url
	String surl = "http://IP:Port/ibis/faceService/compareFaces";

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入服务器接口URL:");
		String surl = sc.nextLine();
		System.out.println("请输入图片img1所在文件夹的路径:");
		String folderPath1 = sc.nextLine();
		folderPath1 = folderPath1.replace("\\", "/");
		System.out.println("请输入图片img1的名称:");
		String imageName1 = sc.nextLine();
		System.out.println("请输入图片img2所在文件夹的路径:");
		String folderPath2 = sc.nextLine();
		folderPath2 = folderPath2.replace("\\", "/");
		System.out.println("请输入图片img2的名称:");
		String imageName2 = sc.nextLine();
		// 执行图片上传接收方法
		postOut(surl, folderPath1, imageName1, folderPath2, imageName2);
		sc.close();
	}

	public static void postOut(String surl, String folderPath1, String imageName1, String folderPath2,
			String imageName2) {
		test_parm mp = new test_parm();
		// 获取文件夹图片调用接口次数
		int num = 0;
		// 接口调用不成功SocketException次数,达到门限就告警
		int i = 0;
		// 5分钟计时器,j>300秒时,如果异常计数器未达到门限值则,计数器清零
		int j = 0;
		// 脸脸比对返回code不是0,的门限告警值
		int k = 0;
		// 调用接口未能返回200 OK消息
		int l = 0;
		// EX的门限告警
		int m = 0;

		do {
			// 开始比对时间点t1
			long t1 = System.currentTimeMillis();
			// 比对次数num++;
			num = mp.getNum() + 1;
			mp.setNum(num);
			// http属性设置
			try {
				URL url = new URL(surl);
				HttpURLConnection connection;
				connection = (HttpURLConnection) url.openConnection();
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				connection.setUseCaches(false);
				connection.setInstanceFollowRedirects(false);
				connection.setRequestProperty("Accept-Charset", "utf-8");
				connection.setRequestProperty("contentType", "utf-8");
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				connection.setConnectTimeout(10000);
				connection.setReadTimeout(10000);
				connection.connect();
				Date date = new Date();
				SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSSS");
				DataOutputStream out = new DataOutputStream(connection.getOutputStream());
				String imgpath1 = "";
				String imgpath2 = "";
				imgpath1 = folderPath1 + "/" + imageName1;
				imgpath2 = folderPath2 + "/" + imageName2;

				// 把jpg图片转换为二进制流
				System.out.println("imgpath1:" + imgpath1);
				System.out.println("imgpath2:" + imgpath2);

				// 构造表单消息体
//				System.out.println("构造消息体前的时间:" + System.currentTimeMillis()
//						+ "***************************************************");
				// 图片base64编码
				String img1 = null;
				String img2 = null;
				try {
					//System.out.println("编码前" + System.currentTimeMillis());
					img1 = URLEncoder.encode(test_PicBASE64.getPicBASE64(folderPath1 + "/" + imageName1), "UTF-8");
					img2 = URLEncoder.encode(test_PicBASE64.getPicBASE64(folderPath2 + "/" + imageName2), "UTF-8");
					//System.out.println("编码后" + System.currentTimeMillis());
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				String data = ("{" + "\"" + "methodName" + "\"" + ":" + "\"" + "compareFaces" + "\"" + "," + "\""
						+ "channel" + "\"" + ":" + "\"" + "0400" + "\"" + "," + "\"" + "img1" + "\"" + ":" + "\"" + img1
						+ "\"" + "," + "\"" + "img2" + "\"" + ":" + "\"" + img2 + "\"" + "}");
				out.writeBytes("requestData" + "=" + data);
				out.flush();
				//System.out.println("HTTP发送时间" + System.currentTimeMillis());
				//long t2 = System.currentTimeMillis();
				out.close();

				// 接收返回值

				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buf = new byte[1024];
				int len = 0;
				//System.out.println("HTTP开始接收时间" + System.currentTimeMillis());
				InputStream is = connection.getInputStream();
				// HTTP返回值
				mp.setCode(new Integer(connection.getResponseCode()).toString());
				// HTTP返回消息
				mp.setMessage(connection.getResponseMessage());
				//System.out.println("HTTP 返回code值为:" + mp.getCode());
				//System.out.println("HTTP 返回message值为:" + mp.getMessage());
				if (!(mp.getCode().equals("200")) || !(mp.getMessage().equals("OK"))) {
					l = mp.getL() + 1;
					mp.setL(l);
					// l++;
					if (mp.getL() > 4) {
						mp.setFlagl(1);
					}
				}
				System.out.println("接收字节数:" +is.available());
				// 接收消息内容
				while ((len = is.read(buf)) != -1) {
					System.out.println("Img1" + "\t" + imageName1 + "\t" + "Img2" + "\t" + imageName2 + "\t" + "比对次数:"
							+ "\t" + num );
					// 返回结果写入txt文件
					baos.write(buf, 0, len);
					//System.out.println("HTTP接收完成时间" + System.currentTimeMillis());
					//System.out.println("HTTP发送接收用时" + (System.currentTimeMillis() - t2) + "毫秒");
					FileOutputStream fos = new FileOutputStream(folderPath1 + "/test.txt", true);
					String str2;
//替换					str2 ="第" + num + "次比对:" + "\t" + "Img1" + "\t" + imageName1 + "\t" + "Img2" + "\t" + imageName2 + "\t" + formater.format(date)
//替换						+ "\t" + baos.toString("UTF-8").replace("\n", "") + "\n";
					str2 ="第" + num + "次比对:" + "\t" + "Img1" + "\t" + imageName1 + "\t" + "Img2" + "\t" + imageName2 + "\t" + formater.format(date)
					+ "\t" + baos.toString("UTF-8") + "\n";
					byte[] word = str2.getBytes();
					fos.write(word, 0, word.length);
					fos.flush();
					fos.close();
				}

				baos.flush();
				//System.out.println("预期的HTTP 200OK 实际返回的内容:" + baos.toString("UTF-8"));
				// 初始化数组的值
				String[] a1 = new String[11];
				a1[0] = "a0";
				a1[1] = "a1";
				a1[2] = "a2";
				a1[3] = "a3";
				a1[4] = "a4";
				a1[5] = "a5";
				a1[6] = "a6";
				a1[7] = "a7";
				a1[8] = "a8";
				a1[9] = "a9";
				a1[10] = "a10";
				// 截取{"code":0,"message":"......","data":{"sim":0.9815}}
				mp.setRs(new String(baos.toString("UTF-8")));
				String a[] = mp.getRs().split("\"");
				// 防止数组越界,不同返回值的分割元素的个数不一样
				try {
					String c0 = a[0].equals(null) ? a1[0] : a[0];
					//System.out.println(c0);
					String c1 = a[1].equals(null) ? a1[1] : a[1];
					//System.out.println(c1);
					String c2 = a[2].equals(null) ? a1[2] : a[2];
					//System.out.println(c2);
					String c3 = a[3].equals(null) ? a1[3] : a[3];
					//System.out.println(c3);
					String c4 = a[4].equals(null) ? a1[4] : a[4];
					//System.out.println(c4);
					String c5 = a[5].equals(null) ? a1[5] : a[5];
					//System.out.println(c5);
					String c6 = a[6].equals(null) ? a1[6] : a[6];
					//System.out.println(c6);
					String c7 = a[7].equals(null) ? a1[7] : a[7];
					//System.out.println(c7);
					String c8 = a[8].equals(null) ? a1[8] : a[8];
					//System.out.println(c8);
					String c9 = a[9].equals(null) ? a1[9] : a[9];
					//System.out.println(c9);
					String c10 = a[9].equals(null) ? a1[10] : a[10];
					//System.out.println(c10);
				} catch (ArrayIndexOutOfBoundsException e) {
					e.printStackTrace();
				} finally {

					String code_value = ":0,";
					if (!a[2].equals(code_value)) {
						k = mp.getK() + 1;
						mp.setK(k);
						// k++;
						if (mp.getK() > 4) {
							mp.setFlagk(1);
						}
					}
					baos.close();
					is.close();
					connection.disconnect();
					//System.out.println("\t" + "HTTP断开时间" + System.currentTimeMillis());
					System.out.println("比对处理用时" + (System.currentTimeMillis() - t1) + "毫秒");
					System.out.println("第" + mp.getNum() + "次比对结束!!!11111111111111111111111111111111111");
				}

			} // catch (IOException e) {
				// e.printStackTrace();
				// }
			catch (SocketException e) {
				e.printStackTrace();
				i = mp.getI() + 1;
				mp.setI(i);
				// i++;
				if (mp.getI() > 4) {
					mp.setFlagi(1);
					// flagi = 1;
				}
			} catch (Exception e) {
				e.printStackTrace();
				m = mp.getM() + 1;
				mp.setM(m);
				// m++;
				if (mp.getM() > 4) {
					mp.setFlagm(1);
					;
					// flagm = 1;
				}
			} finally {
				//System.out.println("进入finally/////////////////////////////////////////");
				// 如果4类异常未发生或恢复,则“5分钟计数器”清零
				if ((mp.getI() == 0) && (mp.getK() == 0) && (mp.getL() == 0) && (mp.getM() == 0)) {
					// j = 0;
					mp.setJ(0);
				}
				// 4类异常
//				System.out.println("i的值:" + mp.getI());
//				System.out.println("j的值:" + mp.getJ());
//				System.out.println("k的值:" + mp.getK());
//				System.out.println("l的值:" + mp.getL());
//				System.out.println("m的值:" + mp.getM());
//				System.out.println("flagi的值:" + mp.getFlagi());
//				System.out.println("flag的值:" + mp.getFlag());
//				System.out.println("flagk的值:" + mp.getFlagk());
//				System.out.println("flagl的值:" + mp.getFlagl());
//				System.out.println("flagm的值:" + mp.getFlagm());
				// 邮件发送对象实例化
				MyAuthenticator sendmail = new MyAuthenticator();
				// j<5表示在5分钟内出现5次异常,发送邮件,就退出程序
				if ((mp.getJ() <= 5)
						&& (mp.getFlagi() != 0 || mp.getFlagk() != 0 || mp.getFlagl() != 0 || mp.getFlagm() != 0)) {
					// 如果超过4类异常门限值,就发送邮件告警通知
					if (mp.getFlagi() == 1) {
						System.out.println(
								"java.net.SocketException!!!!!!!!!!!!!!!!!!!!!!!!!" + System.currentTimeMillis());
						// 发送邮件
						sendmail.sendMail("邮箱内容ibis face 2 face 接口不可用提醒 邮件群发:SocketException,请关注ibis的http连接");
						//发一次就归零
						mp.setFlagi(0);
					}
					if (mp.getFlagm() == 1) {
						System.out.println("Exception!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + System.currentTimeMillis());
						sendmail.sendMail("邮箱内容ibis face 2 face 接口不可用提醒 邮件群发:Exception");
						//发一次就归零
						mp.setFlagm(0);
					}
					if (mp.getFlagl() == 1) {
						System.out.println("脸脸比对未能返回200 OK消息!!!!!!!!!!!!!!!!!!!!!!!!!" + System.currentTimeMillis());
						// 发送邮件
						sendmail.sendMail("邮箱内容ibis face 2 face 接口不可用提醒 邮件群发:" + "调用脸脸比对接口,未能返回200 OK消息-->"
								+ mp.getCode() + mp.getMessage());
						//发一次就归零
						mp.setFlagl(0);
					}
					if (mp.getFlagk() == 1) {
						System.out.println("脸脸比对未能返回分数值!!!!!!!!!!!!!!!!!!!!!!!!!" + System.currentTimeMillis());
						// 发送邮件
						sendmail.sendMail("邮箱内容ibis face 2 face 接口不可用提醒 邮件群发:" + mp.getRs());
						//发一次就归零
						mp.setFlagk(0);
					}
					System.out.println("通知邮件已发送");
					mp.setFlag(1);
					// 如果发一次邮件就退出,则break
					// break;
				}
				// 如果没有满足发邮件的条件,即5分钟内没有发生5次异常,则计算器j清零
				if (((mp.getJ() % 5 == 0) && mp.getJ() > 1)
						&& (mp.getFlagi() == 0 || mp.getFlagk() == 0 || mp.getFlagl() == 0 || mp.getFlagm() == 0)) {
					mp.setJ(0);
					mp.setI(0);
					mp.setK(0);
					mp.setL(0);
					mp.setM(0);
					mp.setFlag(0);
				}
				// 过一分钟,“5分钟计数器j”增加1;当异常>4,j>5时,未达到告警通知门限
				try {
					if((60000-(System.currentTimeMillis() - t1)) > 0 ){
						Thread.sleep(60000-(System.currentTimeMillis() - t1));
					}else{
						Thread.sleep(60000);// 1000 毫秒,也就是1秒.
					}; //总时间控制在60秒
				} catch (InterruptedException ex) {
					Thread.currentThread().interrupt();
				}
				// j++;
				j = mp.getJ() + 1;
				mp.setJ(j);
			}
		}
		// 发一次邮件继续监控接口
		while (1 != 0);
	}
}


2,把图片转换成BASE64编码
package m;

import java.io.FileInputStream;

public class mibis_PicBASE64 {
	public static String getPicBASE64(String picPath1) {
		String picPath = picPath1;
		String content = "";
		try {
			FileInputStream img1ForInput = new FileInputStream(picPath);
			byte[] bytes = new byte[img1ForInput.available()];
			img1ForInput.read(bytes);
			content = new sun.misc.BASE64Encoder().encode(bytes);
//			content = content.replace("\r", "");
//			content = content.replace("\n", "");
			content = content.replace("\\", "%2F");
			img1ForInput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}
}

3,程序参数设置

package m;

public class mibis_parm {
	// 获取文件夹图片调用接口次数
	int num = 0;
	// 接口调用不成功次数,达到门限就告警
	int i = 0;
	int flagi = 0;
	// 5分钟计时器,j>300秒时,如果异常计数器未达到门限值则,计数器清零
	int j = 0;
	// 脸脸比对返回code不是0,的门限告警值
	int k = 0;
	int flagk = 0;
	// 调用接口未能返回200 OK消息
	int l = 0;
	int flagl = 0;
	// EX的门限告警
	int m = 0;
	int flagm = 0;
	// 是否退出程序标识
	int flag = 0;
	//HTTP返回的代码值
	String code = "";
	//HTTP返回的消息
	String message = "";
	//HTTP返回值的字符串
	String rs = "";
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public int getI() {
		return i;
	}
	public void setI(int i) {
		this.i = i;
	}
	public int getFlagi() {
		return flagi;
	}
	public void setFlagi(int flagi) {
		this.flagi = flagi;
	}
	public int getJ() {
		return j;
	}
	public void setJ(int j) {
		this.j = j;
	}
	public int getK() {
		return k;
	}
	public void setK(int k) {
		this.k = k;
	}
	public int getFlagk() {
		return flagk;
	}
	public void setFlagk(int flagk) {
		this.flagk = flagk;
	}
	public int getL() {
		return l;
	}
	public void setL(int l) {
		this.l = l;
	}
	public int getFlagl() {
		return flagl;
	}
	public void setFlagl(int flagl) {
		this.flagl = flagl;
	}
	public int getM() {
		return m;
	}
	public void setM(int m) {
		this.m = m;
	}
	public int getFlagm() {
		return flagm;
	}
	public void setFlagm(int flagm) {
		this.flagm = flagm;
	}
	public int getFlag() {
		return flag;
	}
	public void setFlag(int flag) {
		this.flag = flag;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getRs() {
		return rs;
	}
	public void setRs(String rs) {
		this.rs = rs;
	}
}

4,

package MailSenderInfo;

/**  
* 发送邮件需要使用的基本信息  
*/   
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;   
    }   
}

5,

<pre name="code" class="java">package MailSenderInfo;

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);  
    }  
    
    public void sendMail(String content){  
     //这个类主要是设置邮件  
     MailSenderInfo mailInfo = new MailSenderInfo();   
     mailInfo.setMailServerHost("smtp.163.com");   
     mailInfo.setMailServerPort("25");   
     mailInfo.setValidate(true);   
     mailInfo.setUserName("gongxun");   //自己的邮箱
     mailInfo.setPassword("shineboy");//自己的邮箱密码,用于验证          
     mailInfo.setFromAddress("gongxun@163.com");  ///自己的邮箱
     mailInfo.setToAddress("123@163.com");  ///对方的邮箱
     mailInfo.setSubject("ibis接口监控邮件群发送通知");  
     System.out.println("content:"+content);
     mailInfo.setContent(content);
    // mailInfo.setContent("邮箱内容ibis face 2 face 接口不可用提醒 邮件群发。");
     System.out.println("mailInfo:" + mailInfo.getToAddress());
     //这个类主要来发送邮件  
     SimpleMailSender sms = new SimpleMailSender();  
     sms.sendTextMail(mailInfo);//发送文体格式   
     //sms.sendHtmlMail(mailInfo);//发送html格式
       
   }  
}



6,

package MailSenderInfo;


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  {   
/**  
  * 以文本格式发送邮件  
  * @param mailInfo 待发送的邮件的信息  
  */   
    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);   
      
      Address toAddress = new InternetAddress("@cloud.cn");
      Address ccAddress = new InternetAddress("@cloud.cn");
      Address ccAddress2 = new InternetAddress("@cloud.cn");
      Address ccAddress3 = new InternetAddress("@cloud.cn");

      mailMessage.addRecipient(Message.RecipientType.TO, toAddress);
      mailMessage.addRecipient(Message.RecipientType.CC, ccAddress);
      mailMessage.addRecipient(Message.RecipientType.CC, ccAddress2);
      mailMessage.addRecipient(Message.RecipientType.CC, ccAddress3);
      
      
      // 设置邮件消息的主题   
      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;   
    }   
      
    /**  
      * 以HTML格式发送邮件  
      * @param mailInfo 待发送的邮件信息  
      */   
    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;   
    }   
}


服务器接口状态监控,异常报警到电子邮箱。

标签:

原文地址:http://blog.csdn.net/shineboy4463/article/details/51692503

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!