PackageCom.yxy.monitor.common;ImportOrg.apache.logging.log4j.LogManager;ImportOrg.apache.logging.log4j.Logger;ImportJavax.activation.DataHandler;ImportJavax.activation.FileDataSource;ImportJavax.mail.*;Importjavax.mail.internet.*;Importjava.io.UnsupportedEncodingException;Importjava.util.Date;Importjava.util.List;Importjava.util.Properties;/*** Send mail sharing class * *@authorNortheasttycoon *@version1.0.0 2016/9/21*/ Public classMailcommonutil {protected Final StaticLogger Logger =Logmanager.getlogger (); //Mail Service Private StaticString host; //the name of the user who sent the message Private StaticString username; //password to send the message Private StaticString password; //info and from form the sender information for the mailbox Private StaticString from; Private StaticString Info; Static { Try{host= "Smtp.163.com"; Username= "[Email protected]"; Password= "Northeasttycoon"; from= "[Email protected]"; Info= "Mail Monitoring"; } Catch(Exception e) {e.printstacktrace (); } } /*** Send mail * *@paramto Recipient list, with "," Split *@paramSubject Title *@paramBody Content *@paramfilepath attachment list, no attachments passed null *@return * @throwsmessagingexception *@throwsaddressexception *@throwsunsupportedencodingexception*/ Public Static BooleanSendMail (string to, string subject, String body, List<String> filepath)throwsaddressexception, Messagingexception, unsupportedencodingexception {//parameter Decoration if(BODY = =NULL) {Body= ""; } if(Subject = =NULL) {Logger.info ("The message sent is no subject!"); } //Create a Properties objectProperties props =system.getproperties (); //Create a mail serverProps.put ("Mail.smtp.host", host); Props.put ("Mail.smtp.auth", "true");//by verifying//get the default dialog objectSession session = Session.getdefaultinstance (props,NULL); //creates a message and initializes the elements of the messageMimeMessage msg =NewMimeMessage (session); Info=Mimeutility.encodetext (info); Msg.setfrom (NewInternetAddress (info + "<" + from + ">")); //Create a recipient list if(To! =NULL&& To.trim (). Length () > 0) {string[] arr= To.split (","); intReceivercount =arr.length; if(Receivercount > 0) {internetaddress[] address=NewInternetaddress[receivercount]; for(inti = 0; i < Receivercount; i++) {Address[i]=Newinternetaddress (Arr[i]); } msg.addrecipients (Message.RecipientType.TO, address); Msg.setsubject (subject); //The following bodypart will be added to the multipart created hereMultipart MP =NewMimemultipart (); //Attachment Operation if(FilePath! =NULL&& filepath.size () > 0) { for(String filename:filepath) {MimeBodyPart MBP=NewMimeBodyPart (); //get the data sourceFiledatasource FDS =Newfiledatasource (filename); //get the attachment itself and into the BodyPartMbp.setdatahandler (NewDataHandler (FDS)); //get the same file name into BodyPartMbp.setfilename (Fds.getname ()); Mp.addbodypart (MBP); } MimeBodyPart MBP=NewMimeBodyPart (); Mbp.settext (body); Mp.addbodypart (MBP); //Remove all elements from the collectionfilepath.clear (); //multipart added to the letterMsg.setcontent (MP); } Else { //set the message bodyMsg.settext (body); } //set the sending date of the letter headerMsg.setsentdate (NewDate ()); Msg.savechanges (); //Send a letterTransport Transport = Session.gettransport ("SMTP"); Transport.connect (host, username, password); Transport.sendmessage (msg, msg.getrecipients (Message.RecipientType.TO)); Transport.close (); return true; } Else{logger.error ("There is no receiving address!"); return false; } } Else{logger.error ("There is no receiving address!"); return false; } }}ImportCom.yxy.monitor.common.MailCommonUtil;Importjavax.mail.MessagingException;Importjavax.mail.internet.AddressException;Importjava.io.UnsupportedEncodingException;Importjava.util.ArrayList;Importjava.util.List;/*** Test Mail send Operation class * *@authorNortheasttycoon *@version1.0.0 2016/9/21*/ Public classTestmail { Public Static voidMain (string[] args)throwsaddressexception, Unsupportedencodingexception, messagingexception {List<String> filepath =NewArraylist<>(); //the actual deposited documents geologyFilepath.add ("E:\\ceshi.txt"); Mailcommonutil.sendmail ("[Email Protected],[email protected]", "Test Mail", "Monitoring feature Mail", NULL); }}
I use the Gradle to build the project, above with 163 mailbox For example code, complete the above code needs jar package, add in Build.gradle
Compile (' javax.mail:mail:1.4.7 ')
Java Send mail