java实现系统捕获异常发送邮件案例

在实际运用中,比如你淘宝购物,申请退款,这时你在邮箱中看到退款邮件,或者你注册某个账号,申请验证邮箱通知等等,这些都是邮件发送,这里将介绍下系统捕获异常发送邮件案例。

准备工作:
eclipse4.5 64位
jdk1.7 64位

邮件发送所需jar:

fastjson-1.1.24.jar,javax.mail-1.5.6.jar

类Developer:

枚举类型,发送邮件人姓名和邮箱地址

package mail; 
/** 
 * @class:Developer 
 *@descript:枚举类型,发送邮件人姓名和邮箱地址 
 *@date:2016年10月26日 下午8:07:50 
 *@author sanghaiqin 
 *@version:V1.0 
 */ 
public enum Developer { 
  zhoujing("周静","405687038@qq.com"), 
  peiyuxiang("裴玉翔","498736875@qq.com"), 
  yipeng("乙鹏","729325112@qq.com"), 
  liuan("刘安","2211747233@qq.com"), 
  chenyuhao("陈宇豪","631604198@qq.com"), 
  wangdong("王栋","1217295649@qq.com"), 
  sanghaiqin("桑海芹","1522580013@qq.com"); 
   
  //发件人姓名 
  private String name; 
  //发件人email 
  private String mail; 
   
  private Developer() { 
     
  } 
   
  private Developer(String name, String mail) { 
    this.name = name; 
    this.mail = mail; 
  } 
   
  /** 
   * @descript:传递发件人姓名得到该发件人的邮箱 
   * @param name 发件人姓名 
   * @return 
   */ 
  public static String getMail(String name) { 
    for (Developer c : Developer.values()) { 
      if (c.getName().equals(name)) { 
        return c.mail; 
      } 
    } 
    return null; 
  } 
   
  public String getName() { 
    return name; 
  } 
  public void setName(String name) { 
    this.name = name; 
  } 
  public String getMail() { 
    return mail; 
  } 
  public void setMail(String mail) { 
    this.mail = mail; 
  } 
   
} 

类ExceptionInfo:发件人信息

package mail; 
/** 
 * @class:ExceptionInfo 
 *@descript:发件人信息 
 *@date:2016年10月26日 下午8:11:27 
 *@author sanghaiqin 
 *@version:V1.0 
 */ 
public class ExceptionInfo { 
 
  //发件人姓名 
  private String developer; 
  //发件人方法 
  private String method; 
  //发件人url 
  private String url; 
  //发件人捕获异常信息 
  private Exception e; 
   
  /** 
   * @param developer 发件人姓名 
   * @param method 发件人方法 
   * @param url 发件人url 
   * @param e 发件人捕获异常信息 
   */ 
  public ExceptionInfo(String developer, String method, String url, Exception e) { 
    super(); 
    this.developer = developer; 
    this.method = method; 
    this.url = url; 
    this.e = e; 
  } 
  public String getDeveloper() { 
    return developer; 
  } 
  public void setDeveloper(String developer) { 
    this.developer = developer; 
  } 
  public String getMethod() { 
    return method; 
  } 
  public void setMethod(String method) { 
    this.method = method; 
  } 
  public String getUrl() { 
    return url; 
  } 
  public void setUrl(String url) { 
    this.url = url; 
  } 
  public Exception getE() { 
    return e; 
  } 
  public void setE(Exception e) { 
    this.e = e; 
  } 
   
   
} 

类MailSenderInfo:发送邮箱信息

package mail; 
 
import java.util.Properties; 
/** 
 * @class:MailSenderInfo 
 *@descript:发送邮箱信息 
 *@date:2016年10月26日 下午8:14:22 
 *@author sanghaiqin 
 *@version:V1.0 
 */ 
public class MailSenderInfo { 
  //发送邮件的服务器的IP 
  private String mailServerHost; 
  //发送邮件的服务器的端口默认为25 
  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 MailSenderInfo() { 
    super(); 
  } 
 
  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; 
  } 
   
  /** 
   * @descript:获得邮件会话属性 
   * @return 
   */ 
  public Properties getProperties() { 
    PropertyUtil propertyUtil = new PropertyUtil(); 
    Properties properties =propertyUtil.readProperties(); 
    return properties; 
  } 
 
   
   
} 

类MyAuthenticator:用户验证

package mail; 
 
import javax.mail.Authenticator; 
import javax.mail.PasswordAuthentication; 
/** 
 * @class:MyAuthenticator 
 *@descript:用户验证 
 *@date:2016年10月26日 下午8:57:45 
 *@author sanghaiqin 
 *@version:V1.0 
 */ 
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); 
  } 
   
} 

类PropertyUtil:获得properties文件工具类

package mail; 
 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.Properties; 
/** 
 * @class:PropertyUtil 
 *@descript:获得properties文件工具类 
 *@date:2016年10月26日 下午8:20:10 
 *@author sanghaiqin 
 *@version:V1.0 
 */ 
public class PropertyUtil { 
  /** 
   * @descript:加载资源文件 
   * @param resources 资源文件 
   * @return 
   * @throws FileNotFoundException 
   */ 
  private Properties loadProperties(String resources) { 
    InputStream inputstream = null; 
    Properties properties = new Properties(); 
    // 使用InputStream得到一个资源文件 
    try { 
      inputstream = new FileInputStream(resources); 
       // 加载配置文件 
       properties.load(inputstream); 
    } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    }finally{ 
      if(inputstream!=null){ 
        try { 
          inputstream.close(); 
        } catch (IOException e) { 
          e.printStackTrace(); 
        }  
      } 
    } 
    return properties; 
  } 
   
  /** 
   * @descript:读属性文件 
   * @return 
   * @throws FileNotFoundException 
   */ 
  public Properties readProperties(){ 
    String resources = PropertyUtil.class.getClassLoader().getResource("prop.properties").getPath(); 
    Properties properties = loadProperties(resources); 
    return properties; 
  } 
   
  /** 
   * @descript:测试 
   * @param args 
   */ 
  public static void main(String[] args) { 
    PropertyUtil p=new PropertyUtil(); 
    Properties pro=p.readProperties(); 
    String mailSenderUsername=(String) pro.get("mail.sender.username"); 
    System.out.println("邮件发送者用户名:"+mailSenderUsername);//neo_lifes@163.com 
    String path = PropertyUtil.class.getClassLoader().getResource("prop.properties").getPath(); 
    System.out.println(path);// /G:/Workspaces4.4/test/bin/prop.properties 
  } 
   
} 

资源文件pro.properties:

#-------------------邮件功能------------------ 
#----------------这两个是构建session必须的字段---------- 
#smtp服务器,构建session回话必须的字段 
mail.smtp.host=smtp.163.com 
#身份验证,构建session回话必须的字段 
mail.smtp.auth=true 
#-------------------------------------------------------------- 
#发送者的邮箱用户名 
mail.sender.username=neo_lifes@163.com 
#发送者的邮箱密码 
mail.sender.password=827623LIU 
#发送者的邮箱地址 
mail.sender.address=neo_lifes@163.com 

类JavaMail:发送邮箱

package mail; 
 
import java.io.PrintWriter; 
import java.io.StringWriter; 
import java.io.UnsupportedEncodingException; 
import java.net.InetAddress; 
import java.net.UnknownHostException; 
import java.util.Date; 
import java.util.Properties; 
 
import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
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; 
import javax.mail.internet.MimeUtility; 
 
/** 
 * @class:JavaMail 
 *@descript:发送信息邮箱 
 *所需jar包: 
 *fastjson-1.1.24.jar 
 *javax.mail-1.5.6.jar 
 *@date:2016年10月26日 下午8:13:05 
 *@author sanghaiqin 
 *@version:V1.0 
 */ 
public class JavaMail { 
   
  public static void sendExceptionMail(ExceptionInfo info){ 
    try { 
      //通过发送者获得发送者邮箱 
      String mail = Developer.getMail(info.getDeveloper()); 
      if(mail!=null){ 
        MailSenderInfo mailInfo = new MailSenderInfo(); 
        //设置邮件的文本内容 
        mailInfo.setContent("负责人 : "+info.getDeveloper()+"==>服务器 ip:"+InetAddress.getLocalHost().getHostAddress()+"==>方法名: "+info.getMethod()+"==>地址:"+info.getUrl()+"==>异常信息: "+getEmessage(info.getE())); 
        //设置邮件接收者的地址 
        mailInfo.setToAddress(mail); 
        //邮件主题 
        mailInfo.setSubject("易卡爱途异常通知"); 
        //发送邮件 
        sendTextMail(mailInfo); 
      } 
    } catch (UnknownHostException e) { 
      e.printStackTrace(); 
    } 
  } 
   
  /** 
   * @descript:以文本格式发送邮件 
   * @param: mailInfo 待发送的邮件的信息 
   * @return: 发送成功返回true;失败返回false 
   */ 
  public static boolean sendTextMail(MailSenderInfo mailInfo) { 
    // 判断是否需要身份认证 
    MyAuthenticator authenticator = null; 
    Properties pro = mailInfo.getProperties(); 
    try {  
      if ("true".trim().equals(pro.getProperty("mail.smtp.auth"))) { 
        // 如果需要身份认证,则创建一个密码验证器 
        authenticator = new MyAuthenticator(pro.getProperty("mail.sender.username"),pro.getProperty("mail.sender.password")); 
      } 
      // 根据邮件会话属性和密码验证器构造一个发送邮件的session 
      Session sendMailSession = Session.getDefaultInstance(pro, authenticator); 
      // 根据session创建一个邮件消息 
      Message mailMessage = new MimeMessage(sendMailSession); 
      // 创建邮件发送者地址 
      Address from = new InternetAddress(pro.getProperty("mail.sender.address")); 
      // 设置邮件消息的发送者 
      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()); 
      // 设置邮件消息的主要内容 
      mailMessage.setText(mailInfo.getContent()); 
      // 发送邮件 
      Transport.send(mailMessage); 
      return true; 
    } catch (MessagingException ex) { 
      ex.printStackTrace(); 
    } 
    return false; 
  } 
 
  /** 
   * @descript:以HTML格式发送邮件 
   * @param mailInfo: 待发送的邮件的信息 
   * @param attachment:附件内容 
   * @return:发送成功返回true;失败返回false 
   */ 
  public static boolean sendHtmlMail(MailSenderInfo mailInfo, String[] attachment) { 
    // 判断是否需要身份认证 
    MyAuthenticator authenticator = null; 
    Properties pro = mailInfo.getProperties(); 
    try { 
      // 如果需要身份认证,则创建一个密码验证器 
      if ("true".trim().equals(pro.getProperty("mail.smtp.auth"))) { 
        // 如果需要身份认证,则创建一个密码验证器 
        authenticator = new MyAuthenticator(pro.getProperty("mail.sender.username"),pro.getProperty("mail.sender.password")); 
      } 
      // 根据邮件会话属性和密码验证器构造一个发送邮件的session 
      Session sendMailSession = Session.getDefaultInstance(pro, authenticator); 
      // 根据session创建一个邮件消息 
      Message mailMessage = new MimeMessage(sendMailSession); 
      // 创建邮件发送者地址 
      Address from = new InternetAddress(pro.getProperty("mail.sender.address")); 
      // 设置邮件消息的发送者 
      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"); 
      //添加HTML内容的MimeBodyPart 
      mainPart.addBodyPart(html); 
      // 添加附件的内容 
      if (attachment != null) { 
        for (String filePath : attachment) { 
          MimeBodyPart filePart = new MimeBodyPart(); 
          DataSource source = new FileDataSource(filePath); 
          filePart.setDataHandler(new DataHandler(source)); 
          try { 
            // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定 
            filePart.setFileName(MimeUtility.encodeWord(source.getName())); 
          } catch (UnsupportedEncodingException e) { 
            e.printStackTrace(); 
          } 
          mainPart.addBodyPart(filePart); 
        } 
      } 
      // 将MiniMultipart对象设置为邮件内容 
      mailMessage.setContent(mainPart); 
      //保持内容 
      mailMessage.saveChanges(); 
      // 发送邮件 
      Transport.send(mailMessage); 
      return true; 
    } catch (MessagingException ex) { 
      ex.printStackTrace(); 
    } 
    return false; 
  } 
   
   
  /** 
   * @descript:获得发送者方法的异常信息 
   * 使用字符串作为物理节点的字符输入输出流的用法,即StringReader和StringWriter的用法 
   * PrintWriter(Writer out, boolean autoFlush) 创建带自动行刷新的新 PrintWriter, true代表能自动刷新 
   * @param e 异常信息 
   * @return 
   */ 
  private static String getEmessage(Exception e){   
    //StringWriter输出异常信息 
    StringWriter sw = new StringWriter();   
    PrintWriter pw = new PrintWriter(sw, true);   
    e.printStackTrace(pw);   
    pw.flush();   
    sw.flush();   
    return sw.toString();   
  }  
   
  /** 
   * @descript:测试 
   * @param args 
   */ 
  public static void main(String[] args) { 
    //测试1:发送邮件以文本格式 
    try { 
      String s=""; 
      s.substring(2); 
    } catch (Exception e) { 
      e.printStackTrace(); 
      System.out.println(getEmessage(e)); 
      sendExceptionMail(new ExceptionInfo( Developer.sanghaiqin.getName(),"get()", "123",e)); 
    } 
     
    //测试2:发送邮件以html格式 
    MailSenderInfo mailInfo = new MailSenderInfo(); 
    mailInfo.setToAddress("1522580013@qq.com");       // 设置接受者邮箱地址 
    mailInfo.setSubject("标题");  
    mailInfo.setContent("内容<h1>www.baidu.com</h1>"); 
    String[] files = {"G:/upload/image/2016/10/28/1477372845440.jpg","G:/upload/image/2016/10/28/1477372845660.jpg"}; 
    JavaMail.sendHtmlMail(mailInfo,files); // 发送html格式 
     
    System.out.println("发送成功"); 
     
     
  } 
   
} 

测试截图:

测试1:发送邮件以文本格式:

测试2:发送邮件以html格式:


项目结构截图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。