Java Implementation System capture exception send mail case _java

Source: Internet
Author: User
Tags auth flush mailmessage

In practical use, such as your Taobao shopping, apply for a refund, when you see a refund mail in the mailbox, or you register an account, apply for verification email notification and so on, these are mail sent, here will be introduced under the system to catch abnormal send mail case.

Preparatory work:
eclipse4.5 64-bit
jdk1.7 64-bit

Message to send the required jar:

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

Class Developer:

Enumeration type, sending mail person name and email address

Package mail; /** * @class:D Eveloper * @descript: Enumeration type, sender name and email address * @date: October 26, 2016 afternoon 8:07:50 * @author sanghaiqin * @version: V 1.0 * * Public enum Developer {zhoujing ("Zhou Jing", "405687038@qq.com"), Peiyuxiang ("Pei Yuxiang", "498736875@qq.com"), Yipeng ("B-Peng", "729325112@qq.com"), Liuan ("Liu an", "2211747233@qq.com"), Chenyuhao ("Chen Yuhao", "631604198@qq.com"), Wangdong ("Wangdong", "1 
   
  217295649@qq.com "), Sanghaiqin (" Sanghai "," 1522580013@qq.com "); 
  Sender name private String name; 
   
  Sender email Private String mail; 
    Private Developer () {} private Developer (string name, String mail) {this.name = name; 
  this.mail = mail; /** * @descript: Passing the sender's name to the sender's mailbox * @param name Sender 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; 
 } 
   
}

Class Exceptioninfo: Sender information

Package mail;  
/** * @class: Exceptioninfo * @descript: Sender information * @date: October 26, 2016 afternoon 8:11:27 * @author sanghaiqin * @version: V1.0/ 
  public class Exceptioninfo {//Sender name private String developer; 
  Sender methods private String method; 
  Sender URL private String URL; 
   
  Sender catches exception information private Exception E; /** * @param developer Sender's name * @param methods Sender method * @param URL Sender url * @param e sender Catch Exception information * * Publ 
    IC 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; 
 } 
   
   
}

Class Mailsenderinfo: Sending mailbox information

Package mail; 
Import java.util.Properties; 
 /** * @class: Mailsenderinfo * @descript: Send mailbox information * @date: October 26, 2016 afternoon 8:14:22 * @author sanghaiqin * @version: V1.0 
  * * public class Mailsenderinfo {//IP private String mailserverhost of the server sending mail; 
  The port of the server sending the message defaults to the private String Mailserverport = "25"; 
  The address of the sender of the message is private String fromaddress; 
  The address of the mail recipient is private String toaddress; 
  Login Mail sending server username private String username; 
  Login mail send server password private String password; 
  Whether to require authentication private Boolean validate = false; 
  Message subject private String subject; 
  The text contents of the message are private String content; 
   
  The file name of the message attachment private string[] attachfilenames; 
  Public Mailsenderinfo () {super (); 
  Public String Getmailserverhost () {return mailserverhost; 
  } public void Setmailserverhost (String mailserverhost) {this.mailserverhost = Mailserverhost; 
  Public String Getmailserverport () {return mailserverport; } publicvoid Setmailserverport (String mailserverport) {this.mailserverport = Mailserverport; 
  public Boolean isvalidate () {return validate; 
  } public void Setvalidate (Boolean validate) {this.validate = validate; 
  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: Get mail Session properties * @return/Public Properties GetProperties () {Propertyutil proper 
    Tyutil = new Propertyutil (); 
    Properties Properties =propertyutil.readproperties (); 
  return properties; 
 } 
 
   
   
}

Class Myauthenticator: User authentication

Package mail; 
 
Import Javax.mail.Authenticator; 
Import javax.mail.PasswordAuthentication; 
/** 
 * @class: Myauthenticator 
 * @descript: User authentication 
 * @date: October 26, 2016 afternoon 8:57:45 
 * @author sanghaiqin 
 * @version: V1.0 
 * 
/public class Myauthenticator extends Authenticator { 
  //user name 
  String username = null; 
  Password 
  String password = null; 
 
  Public Myauthenticator () { 
     
  } public 
 
  Myauthenticator (string Username, string password) { 
    This.username = Username; 
    This.password = password; 
  } 
 
  Protected Passwordauthentication getpasswordauthentication () {return 
    to New Passwordauthentication (username, password); 
  } 
   
 

Class Propertyutil: Get Properties File Tool class

Package mail; 
Import Java.io.FileInputStream; 
Import java.io.FileNotFoundException; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.util.Properties; /** * @class:P ropertyutil * @descript: Get Properties File Tool class * @date: October 26, 2016 afternoon 8:20:10 * @author Sanghaiqin * @versio n:v1.0/public class Propertyutil {/** * @descript: Load resource file * @param resources file * @return * @th Rows FileNotFoundException * * Private Properties loadproperties (String resources) {InputStream InputStream = 
    Null 
    Properties Properties = new properties (); 
       Use InputStream to get a resource file try {InputStream = new FileInputStream (resources); 
    Load configuration file 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: Read Properties file * @return * @throws filenotfoundexception * * Public Properties Readprope 
    Rties () {String resources = PropertyUtil.class.getClassLoader (). GetResource ("Prop.properties"). GetPath (); 
    Properties Properties = loadproperties (resources); 
  return properties; /** * @descript: Test * @param args/public static void main (string[] args) {Propertyutil p=n 
    EW Propertyutil (); 
    Properties pro=p.readproperties (); 
    String Mailsenderusername= (String) pro.get ("Mail.sender.username"); System.out.println ("Mail sender Username:" +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}}

Resource file Pro.properties:

#-------------------Mail function------------------ 
#----------------These two are the fields that are required to build the session---------- 
#smtp服务器, Building the required fields for session 
mail.smtp.host=smtp.163.com 
#身份验证, building the required field for session reply 
mail.smtp.auth=true 
#----- --------------------------------------------------------- 
#发送者的邮箱用户名 
mail.sender.username=neo_ lifes@163.com 
#发送者的邮箱密码 
mail.sender.password=827623liu 
#发送者的邮箱地址 
mail.sender.address=neo_ Lifes@163.com 

Class JavaMail: Sending Mailboxes

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: Send information mailbox * required JAR pack: *fastjson-1.1.24.jar *javax.mail-1.5.6.jar * @date: October 26, 2016 PM 8:13:05 * @author Sanghaiqin * @version: V1.0 * * public class JavaMail {public static void Sendexceptionmail (Exceptioninfo info) {try {//Send by sender mailbox String mail = developer.g 
      Etmail (Info.getdeveloper ()); 
        if (mail!=null) {mailsenderinfo mailinfo = new Mailsenderinfo (); Set the text content of the message mailinfo.setcontent ("Owner:" +info.getdeveloper () + ==> server IP: "+inetaddress.getlocalhost (). Gethostad 
        Dress () + "==> Method Name:" +info.getmethod () + "==> Address:" +info.geturl () + "==> exception information:" +getemessage (Info.gete ())); 
        Set the address of the Mail recipient mailinfo.settoaddress (mail); 
        e-mail Theme Mailinfo.setsubject ("Easy to love passers-by abnormal notice"); 
      Send mail Sendtextmail (mailinfo); 
    } catch (Unknownhostexception e) {e.printstacktrace (); 
  /** * @descript: Send a message in text * @param: Mailinfo message to be sent * @return: Send successfully return true; failed return false */ public static Boolean Sendtextmail (Mailsenderinfo mailinfo) {//To determine whether an identity authentication is required myauthenticator authenticator = nul 
    L Properties Pro = Mailinfo.getpRoperties (); try {if ("true". Trim (). Equals (Pro.getproperty ("Mail.smtp.auth")) {//If authentication is required, create a password validator auth 
      Enticator = new Myauthenticator (Pro.getproperty ("Mail.sender.username"), Pro.getproperty ("Mail.sender.password")); Sendmailsession = Session.getdefaultinstance (pro, authenticator), based on message session properties and password validators. 
      ; 
      Create a mail message based on session MailMessage = new MimeMessage (sendmailsession); 
      Create mail Sender address from = new InternetAddress (Pro.getproperty ("mail.sender.address")); 
      Set the sender of the mail message Mailmessage.setfrom (from); 
      Create the recipient address of the message, and set it to the mail message in addresses to = new InternetAddress (mailinfo.gettoaddress ()); 
      The Message.RecipientType.TO property indicates that the recipient's type is to Mailmessage.setrecipient (Message.RecipientType.TO, to); 
      Set the subject of the mail message Mailmessage.setsubject (Mailinfo.getsubject ()); 
      Sets the time mailmessage.setsentdate to send mail messages (new Date ()); Set the primary message messageTo Content Mailmessage.settext (Mailinfo.getcontent ()); 
      Send mail Transport.send (mailmessage); 
    return true; 
    catch (Messagingexception ex) {ex.printstacktrace (); 
  return false; /** * @descript: Send a message in HTML @param mailinfo: Message to be sent * @param attachment: Attachment content * @return: Send a successful return T Rue failure return false */public static Boolean Sendhtmlmail (Mailsenderinfo mailinfo, string[] attachment) {//judge if you need body 
    Certificate Myauthenticator authenticator = null; 
    Properties Pro = Mailinfo.getproperties (); try {//If authentication is required, create a password validator if ("true". Trim (). Equals (Pro.getproperty ("Mail.smtp.auth")) {//if required Identity authentication, create a password validator authenticator = new Myauthenticator (Pro.getproperty ("Mail.sender.username"), Pro.getproperty ("Mail 
      . Sender.password ")); Sendmailsession = Session.getdefaultinstance (pro, authenticator), based on message session properties and password validators. 
      ; Create a mail message based on session MeSsage MailMessage = new MimeMessage (sendmailsession); 
      Create mail Sender address from = new InternetAddress (Pro.getproperty ("mail.sender.address")); 
      Set the sender of the mail message Mailmessage.setfrom (from); 
      Create the recipient address of the message, and set it to the mail message in addresses to = new InternetAddress (mailinfo.gettoaddress ()); 
      The Message.RecipientType.TO property indicates that the recipient's type is to Mailmessage.setrecipient (Message.RecipientType.TO, to); 
      Set the subject of the mail message Mailmessage.setsubject (Mailinfo.getsubject ()); 
      Sets the time mailmessage.setsentdate to send mail messages (new Date ()); 
      The Minimultipart class is a container class that contains objects of the MimeBodyPart type Multipart mainpart = new Mimemultipart (); 
      Create a MimeBodyPart bodypart HTML content containing HTML = new MimeBodyPart (); Set HTML content html.setcontent (Mailinfo.getcontent (), "text/html; 
      Charset=utf-8 "); 
      MimeBodyPart Mainpart.addbodypart (HTML) that adds HTML content; 
   Add the contents of the attachment if (attachment!= null) {for (String filepath:attachment) {       MimeBodyPart Filepart = new MimeBodyPart (); 
          DataSource Source = new Filedatasource (FilePath); 
          Filepart.setdatahandler (new DataHandler (source)); try {//online to solve the file name garbled method, in fact, with Mimeutility.encodeword can be very convenient to fix filepart.setfilename (Mimeutility.enc 
          Odeword (Source.getname ())); 
          catch (Unsupportedencodingexception e) {e.printstacktrace (); 
        } mainpart.addbodypart (Filepart); 
      The Minimultipart object is set to the message content mailmessage.setcontent (Mainpart); 
      Keep content mailmessage.savechanges (); 
      Send mail Transport.send (mailmessage); 
    return true; 
    catch (Messagingexception ex) {ex.printstacktrace (); 
  return false; /** * @descript: Get exception Information for Sender method * Use string as the character input output stream of the physical node, i.e. StringReader and stringwriter usage * printwriter 
(Writer out, Boolean AutoFlush) creates a new printwriter with automatic row refreshes, true to automatically refresh * @param e exception information   * @return */private static String Getemessage (Exception e) {//stringwriter output exception information StringWriter SW =   
    New StringWriter ();   
    PrintWriter pw = new PrintWriter (SW, True);   
    E.printstacktrace (PW);   
    Pw.flush ();   
    Sw.flush ();   
  return sw.tostring ();  
    /** * @descript: Test * @param args/public static void main (string[] args) {//TEST 1: Send message in text format 
      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)); 
    ///Test 2: Send mail in html format mailsenderinfo mailinfo = new Mailsenderinfo ();       Mailinfo.settoaddress ("1522580013@qq.com");  
    Set the recipient's mailbox address Mailinfo.setsubject ("title"); 
    Mailinfo.setcontent ("Content  

Test screenshot:

Test 1: Send the message in text format:

Test 2: Send the message in HTML format:


Project Structure screenshot:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.