Java implementation of the ability to send mail: First need to import Mail.jar;
Then you need to write the sending method:
1, the Mailbox Send Packaging tool class:
PackageCom.wxjiameng.utils;ImportJava.util.Date;ImportJava.util.Properties;ImportJavax.activation.DataHandler;ImportJavax.activation.FileDataSource;Importjavax.mail.Address;ImportJavax.mail.BodyPart;ImportJavax.mail.Message;ImportJavax.mail.MessagingException;ImportJavax.mail.Multipart;ImportJavax.mail.Session;ImportJavax.mail.Transport;Importjavax.mail.internet.InternetAddress;ImportJavax.mail.internet.MimeBodyPart;ImportJavax.mail.internet.MimeMessage;ImportJavax.mail.internet.MimeMultipart;Importjavax.mail.internet.MimeUtility;ImportOrg.apache.log4j.Logger;/** * * @ class Number: * @ class Name: Emailsutils * @ Content Summary: Send message * @author: Lu Weiwei * @ created: April 25, 2016 6:06:15 * @ Modified By: * @ Modified Date : * @ Modify Description: Simple description of Modified content * @version 1.0.0 * */ Public class emailsutils { Public StaticLogger Logger = Logger.getlogger (Emailsutils.class);//multipart objects, message contents, headers, attachments, and so on are added to the MimeMessage object PrivateMultipart MP =NewMimemultipart ();Private FinalString Char_set ="UTF-8";/** * * @Description: Send e-mail * @param emailparaform Sender parameters * @return * @author: Yupeng * @date 2012-5-25 pm 5:13:36 * * Public Boolean sendemails(Emailparaform emailparaform) {BooleanISSUCC =false;if(Emailparaform = =NULL){returnISSUCC; }Try{//javamail needs the properties to create a Session object. It looks for the string "Mail.smtp.host" and the property value is the host that sent the message. The //properties object obtains information such as the mail server, user name, password, and other information that can be shared throughout the application. Properties props=NewProperties ();//can also be used properties props = System.getproperties ();Props.put ("Mail.smtp.host", Emailparaform.getstmphost ());//store information for the sending mail serverProps.put ("Mail.smtp.port",""+ Emailparaform.gettport ());//Port numberProps.put ("Mail.transport.protocol", Emailparaform.getprotocol ()); Props.put ("Mail.smtp.auth", Emailparaform.getneedauth ());//Pass verification at the same time if(NULL! = Emailparaform.getagentip () && emailparaform.getagentip (). Length ()! =0&&!emailparaform.getagentip (). Equals ("0") {Props.put ("Mail.agentip", Emailparaform.getagentip ()); }if(NULL! = Emailparaform.getagentport () && emailparaform.getagentport (). Length ()! =0&&!emailparaform.getagentport (). Equals ("0") {Props.put ("Mail.agentport", Emailparaform.getagentport ()); }//Method Two: (If you are configuring JavaMail in Weblogin: You need to specify the Jndi name to retrieve //context ctx=new InitialContext (); //session s= (Session) ctx.lookup ("MailSession"); //message msg=new mimemessage (s); //This session class represents a message session in JavaMail. Each JavaMail-based application has at least one session but can have any number of sessions. the//session class defines the global and message-related properties of each user. This property describes how the room machine and the server communicate information. //authenticator is also an abstract class, and you need to write your own subclass of ready-made applications. Session s = session.getinstance (props,NULL);//Create a new mail session based on a property, the null parameter is a authenticator (validator) objectString isdebug = Emailparaform.getisdebug ();if(Isdebug! =NULL&& Isdebug.trim (). Equalsignorecase ("true") {S.setdebug (true);//Set debug flag, to see the Mail Server Mail command, you can use this method}//Once you've created your session object, it's time to create the message you want to send. The message type (MimeMessage is one of the types) is used. The //Message object stores the e-mail messages that we actually send, and the message object is created as a MimeMessage object and needs to know which JavaMail session should be selected. The//message class represents a single mail message whose properties include type, address information, and the defined directory structure. Message message=NewMimeMessage (s);//Create a new Message object from a mail session //message.setcontent ("Hello", "Test/plain");//Set the content type of the message, if the format is sent in HTML format must be set, //message.settext ("Hello");//Send messages in general text format //Set up the message, once you have created the Session and message, and filled in the message, you can use address to determine the letter. //If you want a name to appear after the e-mail address, you can also pass it to the constructor: //address from=new internetaddress ("[Email protected]", "Qdison");//e-mail address of senderAddress from=NewInternetAddress (Emailparaform.gettfrom ());//Sender's e-mail addressMessage.setfrom (from);//Set senderAddress to=NewInternetAddress (Emailparaform.gettto ());//Recipient's email addressMessage.setrecipient (message.recipienttype.to,to);//Set the recipient and set its receive type to, and there are 3 predefined types as follows: //message.recipienttype.to Recipients //message.recipienttype.cc cc //message.recipienttype.bcc Dark SendMessage.setsubject (Emailparaform.getttitle ());//Set ThemeMessage.setsentdate (NewDate ());//Set the sending timeSetbody (Emailparaform.gettcontent ());//string fileattachment = "c:\\ test \ Chinese. txt"; //Add AttachmentsString fileattachments = emailparaform.getfileattachments ();if(NULL!=fileattachments) {string[] Fileattarr = Fileattachments.split (";"); for(inti =0; i < fileattarr.length; i++) {String Fileatt = fileattarr[i]; Addfileaffix (Fileatt); }} message.setcontent (MP); Message.savechanges ();//Store mail information //Transport is used to send information, //for mail sending and receiving operation. Transport Transport=s.gettransport (Emailparaform.getprotocol ()); Transport.connect (Emailparaform.getstmphost (), Emailparaform.getusername (), Emailparaform.getpassword ());//Log in to the mailbox in SMTP modeTransport.sendmessage (Message,message.getallrecipients ());//Send mail, where the second parameter is all of the recipient addresses that have been setTransport.close (); ISSUCC =true;; }Catch(Messagingexception e) {Logger.error (e); E.printstacktrace (); }returnISSUCC; }/** * Mail Add attachment * * @param filePath full local file name including pathname * @return Boolean * / Public Boolean Addfileaffix(String FilePath) {Try{BodyPart BP =NewMimeBodyPart (); Filedatasource fileds =NewFiledatasource (FilePath); Bp.setdatahandler (NewDataHandler (fileds)); String filenm = Fileds.getname (); Bp.setfilename (Mimeutility.encodetext (FILENM)); Mp.addbodypart (BP);return true; }Catch(Exception e) {Logger.error (e); System.err.println ("Affix"+ FilePath +"Accour Error"+ e);return false; } }/** * Set Message content * * @param Body Message content * @return boolean */ Public Boolean Setbody(String body) {Try{BodyPart BP =NewMimeBodyPart (); Bp.setcontent (""+ Body,"text/html;charset="+ Char_set); Mp.addbodypart (BP);return true; }Catch(Exception e) {Logger.error (e); System.err.println ("Set mail body is error"+ e);return false; } }/** * Send mail * @param receiveuser recipient * @param title * @param Content * Return True to send successfully, False send failed * @return * / Public Boolean Send(String receiveuser,string title,string content) {BooleanISSUCC =false; Emailparaform SPForm =NewEmailparaform (); Spform.setid ("FFFFFF"); Spform.settfrom ("***@163.com");//Issuer MailboxSpform.setstmphost ("Smtp.163.com");//Mailbox TypeSpform.setneedauth ("true");//Whether certification is requiredSpform.setisdebug ("false");//CommissioningSpform.setprotocol ("SMTP");//AgreementSpform.setusername ("***@163.com");//user nameSpform.setpassword ("****");//PasswordSpform.settport ("very");//Port. Issued by defaultSpform.settto (Receiveuser); Spform.settcontent (content); Spform.setttitle (title); String Formpass = Spform.getpassword ();if(Formpass! =NULL) {issucc=sendemails (SPForm); }returnISSUCC; } Public Static void Main(string[] args) {Emailsutils E =NewEmailsutils (); E.send ("* * @qq. com","Wikipedia","The free Encyclopedia: Wikipedia is a content-free, anyone can participate, and multilingual Encyclopedia Collaboration program ..."); }}
2, the mailbox sends the information entity class:
Package com.wxjiameng.utils; Public classEmailparaform {//Number PrivateString ID;//Sender PrivateString Tfrom;//recipients, separated by semicolons PrivateString Tto;//Theme PrivateString Ttitle;//Content PrivateString tcontent;//Send mail server PrivateString Stmphost;//Accept mail server PrivateString Pophost;//Agreement PrivateString Protocol;//Whether certification is required PrivateString Needauth;//Verify class name //private String authclassnm; PrivateString Isdebug;//CC, separated by semicolons PrivateString TCC;//Dark send, separated by semicolons PrivateString TBCC;//Multiple attachments separated by semicolons PrivateString fileattachments;//user name PrivateString UserName;//Password PrivateString password;//proxy server IP PrivateString Agentip;//Proxy server port number PrivateString Agentport;//weblogin Configuration javamail: You need to specify the Jndi name to retrieve PrivateString JNDINM;//Receive Protocol PrivateString Pprotocol;//Send mail server port PrivateString Tport;//Receive mail server port PrivateString Pport;//set Get Method}
The following exception occurs when you use it:
Need to check the sender's mailbox whether to open POP3/SMTP permissions, open can send success; I do not understand the message to me, learn from each other!
Java Implementation Send mail tool